Wednesday, July 25, 2012

Difference between an Abstract Class and Interface

Probably the second most commonly asked question in an interview after Marker interface is the difference between an Abstract Class and an Interface. To understand the difference clearly, lets start with the definition first.

Abstract Class
An abstract class is a special type of class which cannot be instantiated. This class will contain at least one abstract method (method without a body) but can contain more than one abstract method also. So why do we declare a method abstract... this is a design time decision. When you want subclasses to implement a behaviour, then you declare the super class method to be abstract. An abstract method, if inherited should be implemented. Implementation means that it should override the method with some code.


Interface
An Interface contains only abstract methods. When you want your classes to follow a particular behaviour, you declare an interface with those methods. Let us take the below example.
Say you have few automobiles like Cars, Trucks etc and you want all of them to testDrive(), getFuelled(), then your code will be like below.

Declare the interface
interface Autorules {
public void testDrive();
public void getFuelled();
}

//You would like your Cars and Trucks to follow the rule, so.
public class CarClass implements Autorules {
   
public void testDrive(){
//code for test drive
System.out.println("Test drive looks successful !");
}
public void getFuelled (){
//code for getFuelled
System.out.println("Filling in gas !");
}

}
 
//Now to run the program, create object of the class

public static void main(String args[])
{
//create object of the class
CarClass carobj = new CarClass ();
carobj.testDrive();
carobj.getFuelled();

}
}

Now let us see the key differences

Abstract Class
Interface
An Abstract class can have abstract methods and concrete methods. So an abstract class can have code implementations
An interface contains only abstract methods. It cannot have any method implementation
 Keyword ‘extends’ should be used by the subclass
 Keyword ‘implements’ should be used by the subclass
 As Java does not support multiple inheritance, a class can extend only one interface.
 Java supports multiple implementations. i.e. a class an implement more than one interface.
 Methods and properties defined in an abstract class can be public, private, protected or static.
 All methods and properties defined in an Interface are by default public and abstract.





Similarities
Abstract Class
Interface
An Abstract class not be instantiated
An Interface class not be instantiated

No comments:

Post a Comment