Abstract Classes
Abstract Classes
• There are tons of real-world examples where abstraction is in play whether smartphone
you are using or smart television you are watching all have implemented abstraction
• There are two ways to achieve abstraction in java: –
1.By using interfaces
2.By using abstract classes
Abstract Classes and Methods
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInter
est()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInter
est()+" %");
}}
Interfaces
Syntax
public interface xyz{
public void method();
}
Example :
• A java class can just use the implements keyword to implement the interface and provide the implementation
of the methods of the interface.
Example:
public class Television implements TelevisionRemote{
public void turnOnTelevision(){
//method implementation details
}
public void turnOffTelevision(){
//method implementation details
}
}
• Interfaces provide contract specification or sets of rules for the classes implementing them.
Example
import java.util.*;
interface printable{
void print();
}
class AInterface implements printable{
public void print(){System.out.println("Hello");}
A class extends another class, an interface extends another interface, but a class
implements an interface.
Interface Example: Bank
interface Bank{
float rateOfInterest();
} Add a method loanType() in
class SBI implements Bank{ subclasses to print as
public float rateOfInterest(){return 9.15f;} education loan (ROI=9.15%)
}
class PNB implements Bank{
or housing loan (ROI=9.7%)
public float rateOfInterest(){return 9.7f;}
}
class TestInterface{
public static void main(String[] args){
Bank b=new SBI(); // Bank acts as data type
//SBI c = new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}
Multiple inheritance in Java by interface
interface Printable{
void print();
}
interface Showable{
void show();
}
class A implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}}
• An interface which has no member is known as a marker or tagged interface, for example, Serializable, Cloneable,
Remote, etc. They are used to provide some essential information to the JVM so that JVM may perform some useful
operation.
Nested Interface in Java