Core Java

Difference between Abstract Class and Interface in java

Some of the popular interview questions are “What are the differences between abstract class and interface”, “When will you use abstract class and when will you use interface”. So in this article, we will go through this topic.

Before going through differences between them, let’s go through their introduction.

Abstract class

Abstract classes are created to capture common characteristics of subclasses. It can not be instantiated, it can be only used as super class by its subclasses. Abstract classes are used to create template  for its sub classes down the hierarchy.

Lets take example of JDK class GenericServlet:

public abstract class GenericServlet implements  Servlet, ServletConfig,Serializable{    
// abstract method     
    abstract  void     service(ServletRequest req, ServletResponse res) ; 
    void init()     {
         // Its implementation        
     }  
       // other method related to Servlet    
}

When HttpServlet extends Generic servlet, it provides implementation of service() method:

public class HttpServlet extends GenericServlet
{
       void  service(ServletRequest req, ServletResponse res)
       {
       // implementation 
}
     protected  void  doGet(HttpServletRequest req, HttpServletResponse resp) 
{
    // Implementation 
}

   protected  void  doPost(HttpServletRequest req, HttpServletResponse resp) 
{
    // Implementation 
}

// some other methods related to HttpServlet
}

Interface

An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. So it is kind of signing a contract, you agree that if you implement this interface, then you have to use its methods. It is just a pattern, it can not do anything itself.

Lets take example of Externalizable Interface:

public interface Externalizable
extends Serializable
{

    void writeExternal(ObjectOutput out)
            throws IOException;
    void readExternal(ObjectInput in)
            throws IOException,
            ClassNotFoundException;
}

When you implement this interface, you have to implement the above two methods:

public class Employee implements Externalizable{ 

 int employeeId;
 String employeeName;


 @Override
 public void readExternal(ObjectInput in) throws IOException,
 ClassNotFoundException {  employeeId=in.readInt();
  employeeName=(String) in.readObject();
  
 } @Override
 public void writeExternal(ObjectOutput out) throws IOException {

  out.writeInt(employeeId);
  out.writeObject(employeeName); }
}

Abstract class vs Interface

ParameterAbstract classInterface
Default method ImplementationIt can have default method implementationInterfaces are pure abstraction.It can not have implementation at all.
ImplementationSubclasses use extends keyword to extend an abstract class and they need to provide implementation of all the declared methods in the abstract class unless the subclass is also an abstract classsubclasses use implements keyword to implement interfaces and should provide implementation for all the methods declared in the interface

Constructor
Abstract class can have constructorInterface  can not have constructor
Different from normal java classAbstract classes are almost same as java classes except you can not instantiate it.Interfaces are altogether different type
Access ModifierAbstract class methods can have public ,protected,private and default modifierInterface methods are by default public. you can not use any other access modifier with it
Main() methodAbstract classes can have main method so we can run itInterface do not have main method so we can not run it.
Multiple inheritanceAbstract class can extends one other class and can implement one or more interface.Interface can extends to one or more interfaces only
SpeedIt is faster than interfaceInterface is somewhat slower as it takes some time to find implemented method in class
Adding new methodIf you add new method to abstract class, you can provide default implementation of it. So you don’t need to change your current codeIf you add new method to interface, you have to change the classes which are implementing that interface

 

When to use Abstract class and interface:

  • If you have a lot of methods and want default implementation for some of them, then go with abstract class
  • If you want to implement multiple inheritance then you have to use interface. As java does not support multiple inheritance, subclass can not extend more than one class but you can implement multiple interface so you can use interface for that.
  • If your base contract keeps on changing, then you should use abstract class, as if you keep changing your base contract and use interface, then you have to change all the classes which implements that interface.

Introduction of default and static methods in java 8

Oracle has tried to bridge gap between abstract class and interface by introducing concept of default and static methods in interface. So now we can provide default implementation of a method in interface and will not enforce class to implement it. I will cover this topic in my next post.

Arpit Mandliya

I am java developer at Tata Consultancy Services Ltd. My current area of interest are J2EE,web development and java design patterns. I am technology enthusiast trying to explore new technologies. In spare time,I love blogging.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

11 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
vi
10 years ago

This comparison was valid till Java SE 7. Now with Java SE 8 released, interfaces can contain methods.

I would normally use an abstract class, if the class has any functions with code. I would convert an abstract class to interface, if the abstract class has no functions with code.
Adding functions with code seems to make sense mostly for existing interfaces in legacy system. While writing a new feature, I would hesitate to add functions with code in an interface.

Muralidhar
10 years ago

i saw the same post in his blog without any change of line. I think he copied form his blog and posted here. Anyways nice explanation. Thanks.

vn
vn
10 years ago

Adding a function code in an interface makes sense ONLY when this function is dependent just on the other functions in the same interface.

Stephane
Stephane
10 years ago

Hi,

It is difficult to get the meaning of this sentence:

If your base contract keeps on changing, then you should use abstract class, as if you keep changing your base contract and use interface, then you have to change all the classes which implements that interface.

Can’t we rephrase it as:

If your base contract keeps on changing then you should use an abstract class. Because if your base contract keeps on changing and you still use an interface, you would have to change all the classes which implements that interface every time the contract changes.

Kind Regards,

Stephane

rocky
rocky
10 years ago

good post, thanks.

Ankit Nangli
9 years ago

Nicely done,
Would like to know more about changes made in Java 8 in Interfaces.
Whats the difference between Abstract class and Interface in java 8.

Ankit Nanglia
9 years ago

Nicely done,
Would like to know more about changes made in Java 8 in Interfaces.
Whats the difference between Abstract class and Interface in java 8.
A link to your post on Interfaces in Java 8 will be helpful
Thanks.

shaheed jahagirdar
shaheed jahagirdar
9 years ago

Hi, i want to know if i can extend a class then why should i use abstract class in project…???

please help me in this regard…

Dilli Ganesh
Dilli Ganesh
9 years ago

@shaheed jahagirdar Firstly, we generally dont want to instantiate the super class and so we make the super class as abstract. Secondly, there are certain situations in which we cannot give default implementation for all the methods in the super class and one or more methods in the super class must be made abstract because their implementation must be specific to the sub classes that extends it. So we have to make that methods as abstract so that the classes that extends the super class must implement them. obviously, if the method is made abstract that class must be declared… Read more »

Anurag Singh
7 years ago

this article is very clean and useful.
thank you so much for this nice information.
keep it up.

Priya
6 years ago

abstract class is a class which may or may not have a abstract method.
But interface contains all abstract methods . thanks for sharing this article.

Back to top button