Which one you should use interface or abstract class?

In this post, we are going discuss the practical approach of deciding when to use interface or abstract class.You might have read lot theoretical content on abstract and interface but still confused on taking a step forward to go with interface or abstract.
You have already gone through basic abstraction concept in  Java Object Oriented Principle .Abstraction in Java can be obtained using abstract class and interface.
The interface provides 100% abstraction as all the methods are by default abstract  while abstract class provides abstraction from 0-100% as the abstract class  may contain abstract method as well as non-abstract method.

Consider using Abstract Class when


  • When you have some common methods that you will use in other classes then you can make that method non abstract and keep in abstract class.While other methods you can make abstract and implement as per class.
Let take an example of DAO(Data Access Object) layer to understand this.
We have certain method such as delete();update();find(); save() which we will using all DAO layer classes to perform CRUD operation on different entity objects.So these methods we can keep in abstract dao class.
On the other  hand, we have certain methods which are specific to functionality and varies for different dao classes(like getEmployees()  fetch employees whose age is greater than 25 or getOrder() fetches order date in this months ) so those methods we have have to keep in the interface.
So now our DAOImpl class will extend abstractDao and implement DaoInterface.
  • In abstract class, we can declare non-static and non-final fields which can be used to change the state of the object they belong which us not possible in case of Interface which can have only static and final fields.
For example-

HTTPServlet is an abstract class which has doGet() and  doPost() method which is common to handle any request coming to the server. 

Consider using Interface when

  • When two class which will implement your interface are not related.
  • When you are concerned about behavior but not implementation.
  • The interface has added advantage multiple inheritance as a class can implement multiple interface but can extend only one class.
For example- 

Runnable is an interface which has run method and run method will have different implementation for the different class which is unrelated.

Hope Interface and abstract concept in clear.

You may be interested in Recommended books for Java Interview.

Give you suggestion in comments.If you like the post Share with your friends on social network.

6 Different ways to iterate through HashMap








Which one you should use interface or abstract class? Which one you should use  interface or abstract class? Reviewed by JavaInstance on 10:11:00 AM Rating: 5

No comments:

Powered by Blogger.