Search This Blog

Thursday 8 November 2012

Difference between interface and abstract class in Java ?

Difference between interface and abstract class is most asked question in interview. Even i have face this question five times among 11 interviews.  Defination of abstract class and interface is completely different and easily undestandable but the main issue is to learn where to use abstract,interface.This post will contain a a example to clarify this issue

Main Difference between interface and abstract class


1) Interface allow only declaration of method, where as you can assign a body of a method inside a abstract class

 
public interface TestInterface {

 public String sumOfTwoNumber(int a,int b){    /// Abstract methods do not specify a body. So its not allowed
  int c = a + b;
  System.out.print(c);
  return String.valueOf(c);
 }
 
 public void abs(int a,int b);                 // Allowed
}

 
public abstract class TestAbstract {
 
       public String sumOfTwoNumber(int a, int b) {   // Allowed
  int c = a + b;
  System.out.print(c);
  return String.valueOf(c);
 }
 
 public abstract void sumb();                 // Allowed
}

2) By default every method of interface is abstract. but this is not true for abstract class. we can say that interface is implicitly abstract

3) Interface is fully abstract so we can not instantiate an interface. Making object of abstract class is not possible but it can revoke if its contain main
 like this

public abstract class StaticInner {

 public static void main(String[] args) {
  System.out.print("Invoked");
 }
} 
 

Now comes to general difference

 

1) a class use interface by keyword implements and abstract class with keyword extends

2) one interface can not extends a class but can extends any number of interface

 public interface A {
  public void add();
 }

 public interface B {
  public void minus();
 }

 public interface C extends A, B {
  public void Div();
 }

an abstract class can extends only one class but can implement any number of interface

 public class ABC{
  
 }
 public abstract class CanExtendsOnlyABC extends ABC implements A,B,C{
  
 } 
 
Final Note : Java interface works slow in comparision of abstract class

No comments:

Post a Comment

Feedback always help in improvement. If you have any query suggestion feel free to comment and Keep visiting my blog to encourage me to blogging

Android News and source code