Wednesday 27 January 2016

Difference between abstract classes and interfaces

  1. Abstract classes doesn't support multiple inheritance but interface supports same.
  2. Abstract class can have final/non final and static/non static variables, but interfaces has only static and final variables.
  3. abstract keyword is used to create an abstract class and it can be used with methods also whereas interface keyword is used to create interface and it can’t be used with methods.
  4. Abstract classes can have methods with implementation whereas interface provides absolute abstraction and can’t have any method implementations.
  5. Abstract classes can have methods with implementation whereas interface provides absolute abstraction and can’t have any method implementations.
  6. Abstract classes can extend other class and implement interfaces but interface can only extend other interfaces.
  7. We can run an abstract class if it has main() method but we can’t run an interface because they can’t have main method implementation.

Example of abstract classes and interfaces in java

interface I{
void x();
void y();
void z();
}
abstract class SampleAbstract implements I{
public void z(){System.out.println("Inside z");}
}
class Sample extends SampleAbstract {
public void x(){System.out.println("Inside x");}
public void y(){System.out.println("Inside y");}
public void z(){System.out.println("Inside z");}
}
class TestOne{
public static void main(String args[]){
I a=new Sample ();
a.x();
a.y();
a.z();
}}  

Output:
Inside x
Inside y
Inside z



No comments :

Post a Comment