Java

Java:Difference between Abstract class & Interface

Posted on Updated on

  • A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.
  • The interface in java is a mechanism to achieve abstraction and multiple inheritance in Java.
  • An Abstract class can have both abstract and non abstract methods where as interface has only abstract methods
  • Abstract class does not support multiple inheritance.
  • Abstract class can have protected,public and public abstract methods,static,final or static final variables.
  • Interface can have only public abstract methods and static final (constant)variables by default.

Lets take an example-

abstract class Bank{    
abstract int getRateOfInterest(); 
// Concrete method
Public void getEmi(){  
System.out.println(“EMI”); 
}  
}    
class SBI extends Bank{    
int getRateOfInterest(){return 7;}    
}    
class PNB extends Bank{    
int getRateOfInterest(){return 8;}    
}    
class TestBank{    
public static void main(String args[]){    
Bank b;  
b=new SBI();  
System.out.println(“Rate of Interest is: “+b.getRateOfInterest()+” %”);    
b=new PNB();  
System.out.println(“Rate of Interest is: “+b.getRateOfInterest()+” %”);    
}}    

In the above example the abstract class has an abstract method which is implemented by an other class which extends it and it even has a concrete method.

Now let us see an example of Interface-

interface Bank{  
float rateOfInterest();  
}  
class SBI implements Bank{  
public float rateOfInterest(){return 9.15f;}  
}  
class PNB implements Bank{  
public float rateOfInterest(){return 9.7f;}  
}  
class TestInterface2{  
public static void main(String[] args){  
Bank b=new SBI();  
System.out.println(“ROI: “+b.rateOfInterest());  
}} 

->In this example you can see that the class which implements the interface has the implementation of the abstract method inside the interface.

Abstracted class achieves partial Abstraction where as Interface achieves 100% Abstraction.

Multiple Inheritance in Interface:

If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple inheritance.

 

 multiple inheritance in java

Example of multiple Inheritance:

 

interface Printable{  
void print();  
}  
interface Showable{  
void show();  
}  
class A7 implements Printable,Showable{  
public void print(){System.out.println(“Hello”);}  
public void show(){System.out.println(“Welcome”);}  
  public static void main(String args[]){  
A7 obj = new A7();  
obj.print();  
obj.show();  
 }  
}  
In the above example u can see a class implements 2 interfaces.
Advertisements