Sunday, May 14, 2017

Difference Between Abstract Class vs Interface in Java

When to use interface and abstract class is one of the most popular object-oriented design questions and almost always asked in Java, C#, and C++ interviews. In this article, we will mostly talk in the context of Java programming language, but it equally applies to other languages as well. The question usually starts with a difference between abstract class and interface in Java, which is rather easy to answer, especially if you are familiar with the syntax of the Java interface and abstract class. Things start getting difficult when the interviewer asks about when to use abstract class and interface in Java, which is mostly based upon a solid understanding of popular OOPS concepts like Polymorphism, Encapsulation, Abstraction, Inheritance, and Composition

Many programmers fumbles here, which is natural because most of them haven't gone through the real system design process and haven’t seen the impact of choosing one over another. 

The repercussion of design decisions is best known during the maintenance phase, the good design allows seamless evolution while maintaining a fragile design is a nightmare.

 As I have said previously, sometimes object-oriented design interview questions also helps to understand a topic better, but only if you are willing to do some research and not just mugging the answer. Questions like when to use abstract class and interface fall under the same category. 

In order to best understand this topic, you need to work out some scenarios, examples, etc. It's best to get this kind of knowledge as part of your work but even if you don't get there, you can supplement them by joining a comprehensive course like Design Patterns in Java and doing some object-oriented software design exercises. 

In this article, we will learn the difference between abstract class and interface in Java programming language and based on our understanding of those differences, we will try to find out some tips and guidelines to decide when it's better to use abstract class over the interface or vice-versa.

Difference between abstract class and interface in Java

When to use Abstract Class vs Interface in JavaWhile deciding when to use interface and abstract class, it’s important to know difference between abstract class and interface in Java. In my opinion, following two differences between them drives decision about when to use abstract class or interface in Java.

1) Interface in Java can only contains declaration. You can not declare any concrete methods inside interface. On the other hand abstract class may contain both abstract and concrete methods, which makes abstract class an ideal place to provide common or default functionality. I suggest reading my post 10 things to know about interface in Java to know more about interfaces, particularly in Java programming language.

2) Java interface can extend multiple interface also Java class can implement multiple interfaces, Which means interface can provide more Polymorphism support than abstract class . By extending abstract class, a class can only participate in one Type hierarchy but by using interface it can be part of multiple type hierarchies. E.g. a class can be Runnable and Displayable at same time. One example I can remember of this is writing GUI application in J2ME, where  class extends Canvas and implements CommandListener to provide both graphic and event-handling functionality..

3) In order to implement interface in Java, until your class is abstract, you need to provide implementation of all methods, which is very painful. On the other hand abstract class may help you in this case by providing default implementation. Because of this reason, I prefer to have minimum methods in interface, starting from just one, I don't like idea of marker interface, once annotation is introduced in Java 5. If you look JDK or any framework like Spring, which I does to understand OOPS and design patter better, you will find that most of interface contains only one or two methods e.g. Runnable, Callable, ActionListener etc.

I haven't included all syntactical difference between abstract class and interface in Java here, because focus here to learn when to use abstract class and interface and choosing one over other. Nevertheless you can see difference between interface and abstract class to find  all those syntactical differences.

When to use interface and abstract class in Java

As I said earlier, it's easy to answer questions like difference between abstract class and interface in Java, but difficult to answer follow-ups. Though most of  Java Interview starts with former one, later it goes to see if you have really used abstract class and interface or not. In order to answer this question, you need to have good understanding of OOPS concepts like Polymorphism, Encapsulation, Abstraction and Inheritance. Also familiarity with coupling and cohesion is important. You at least should know that effort of designing should lead to reduce coupling and increased cohesion, ease of maintenance etc. In this part, we will see some scenarios, guidelines, rules which can help you to decide when to use abstract class and interface in Java.

1) In Java particularly, decision between choosing Abstract class and interface may influence by the fact that multiple inheritance is not supported in Java. One class can only extend another class in Java. If you choose abstract class over interface than you lost your chance to extend another class, while at the same time you can implement multiple interfaces to show that you have multiple capability. One of the common example, in favor of interface over abstract class is Thread vs Runnable case. If you want to execute a task and need run() method it's better to implement Runnable interface than extending Thread class.

2) Let's see another case where an abstract class suits better than interface. Since abstract class can include concrete methods, it’s great for maintenance point of view, particularly when your base class is evolving and keep changing. If you need a functionality across all your implementation e.g. a common method, than, you need to change every single implementation to include that change if  you have chosen interface to describe your base class. Abstract class comes handy in this case because you can just define new functionality in abstract super class and every sub class will automatically gets it. In short, abstract class are great in terms of evolving functionality. If you are using interface, you need to exercise extra care while defining contracts because its not easy to change them once published.

3) Interface in Java is great for defining Types. Programming for interfaces than implementation is also one of the useful Object oriented design principle which suggests benefit of using interface as argument to function, return type etc.

4) One more general rule of when to use abstract class and interface is to find out whether a certain class will form a IS-A hierarchy or CAN-DO-THIS hierarchy. If you know that you will be creating classes e.g. Circle, Square than it's better to create an abstract class Shape which can have area() and perimeter() as abstract method, rather than defining Shape as interface in Java. On the other hand if you are going to create classes which can do thinks like, can fly, you can use interface Flyable instead of abstract class.

5) Interface generally define capability e.g. Runnable can run(), Callable can call(), Displayable can display(). So if you need to define capability, consider using interface. Since a class can have multiple capabilities i.e. a class can be Runnable as well as Displayable at same time. As discussed in first point, Since java does not allow multiple inheritance at class level, only way to provide multiple capability is via interfaces.

6) Let's see another example of where to use Abstract class and Interface in Java, which is related to earlier point. Suppose you have lot of classes to model which are birds, which can fly, than creating a base abstract class as Bird would be appropriate  but if you have to model other things along with Birds, which can fly e.g. Airplanes, Balloons or Kites than it's better to create interface Flyable to represent flying functionality. In conclusion, if you need to provide a functionality which is used by same type of class than use Abstract class and if functionality can be used by completely unrelated classes than use interface.

7) Another interesting use of Abstract class and interface is defining contract using interface and providing skeletal using abstract class. java.util.List from Java collection framework is a good example of this pattern. List is declared as interface and extends Collection and Iterable interface and AbstractList is an abstract class which implements List. AbstractList provides skeletal implementation of List interface. Benefit of using this approach is that it minimize the effort to implement this interface by concrete class e.g. ArrayList or LinkedList. If you don't use skeletal implementation e.g. abstract class and instead decide to implement List interface than not only you need to implement all List methods but also you might be duplicating common code. Abstract class in this case reduce effort to implement interface.

8) Interface also provide more decoupling than abstract class because interface doesn't contain any implementation detail, while abstract class may contain default implementation which may couple them with other class or resource.

9) Using interface also help while implementing Dependency Injection design pattern and makes testing easy. Many mock testing framework utilize this behavior.

That's all on When to use Abstract class and interface in Java. Though discussion here is centered around Java but given concept of abstract class and interface goes beyond Java and also applicable to other Object oriented language, some of the tips are also applicable to other OOPS languages. Key thing to remember here is there definition of abstract class and interface e.g. in C++ and C# it varies a lot like in C++ and Java. Single most difference is multiple inheritance. We have also discussed some key differences between abstract class and interface in Java, which influence decision of choosing abstract class over interface or vice-versa. Last thing to remember is that interface is extremely difficult to evolve, so put extra care while designing interfaces.

PS: Effective Java, which is one of the best book on Java programming also has couple of items on interface and abstract class. Joshua Bloch has advised to prefer interface over abstract class in some scenario, which is worth reading.

Further Learning
Design Pattern Library
From 0 to 1: Design Patterns - 24 That Matter - In Java
Java Design Patterns - The Complete Masterclass


MCAndre said...

When should you use abstract classes and interfaces? Always. Subclassing makes testing and reasoning about your code more difficult.

Unknown said...

Think the difference between abstract class and interface may be given point wise. More discussion on their restrictions should be attached.

Parul said...

Great Post Javin. I have faced this question couple of times on interviews, but not able to give proper example, when it comes to choosing interface over abstract class or vice-versa. They always looks similar to me, but I love the way you explain things, If you don't mind, can you take an example and walk though us of using Interface over abstract class, and another example in which abstract class is more suitable than interface? Anyway, learn so many things on object-oriented programming from you, Thank you.

Oguzhan Acargil said...

Well detailed notes about legendary diferrence, thx... my point of view, abstract classes are best fit in low levels of system architecture: persistency, network, web, ui to keep common things under control and reduce redundancy. Interfaces are as is above:)

Javin @ puzzle asked in programming interviews said...

@Oguzhan Acargil, I sort of agree with you. Interface in my opinion can represent highest level of abstraction, and abstract class may be with slightly lower than, given they have some sort o implementation, which as you said good for low levels of system architecture.

Anonymous said...

My reason of using Abstract class is simple, avoid using interfaces until Java 8 comes with default method implementation. I don't like empty methods and no functional code, which is the case with Java interface.

Gauri said...

Hello guys, in state design pattern, should we use an abstract class or interface for modelling State abstraction? this was asked to me in a recent java interview. I said, concrete class because we definitely wants to provide default implementation of State and let's specific state only overrides methods, which make sense on those state. Please le t me know, if my answer is correct?

Anonymous said...

One should always use interface for declaring Types and always code against interface than any particular implementation. Recently I had to refactor lot of code, which was dependent on class which implements interface than the interface itself. Programmers was type casting into specific class, even if they are calling public methods of interface, this code was fragile and broke once I have added another implementation of interface. So use interface on declaring member variable, local variable, method parameters, return type or anywhere you need a Type. Code written using interface are much more flexible than otherwise. Never type cast object into implementation, instead if you need to, cast into interface or abstract class as shown in following code :

* interface
public interface PaymentGateway{ }

* original implementation
public class VisaPaymentGateway implements PaymentGateway{}

* added later
public class MasterPaymentGateway implements PaymentGateway{}

public class CreditCardProcessor{

public void process(CreditCard cc){
PaymentGateway gateway = (PaymentGateway) getComponent("VisaPaymentGateway"); //Ok
VisaPaymentGateway gateway = (VisaPaymentGateway) getComponent("VisaPaymentGateway"); //bad, could have broken




@Javin perfect article , agreed that is most hot question in java world.!! :) ...lem me add few conclusions points to it...

Interface :-
A class can implement multiple interfaces
An interface cannot provide any code at all
An interface can only define public static final constants
An interface cannot define instance variables
Adding a new method has ripple effects on implementing classes (design maintenance)
JAXB cannot deal with interfaces
An interface cannot extends or implement an abstract class
All interface methods are public

In general, interfaces should be used to define contracts
(what is to be achieved, not how to achieve it).

Abstract Class :-

A class can extend at most one abstract class
An abstract class can contain code
An abstract class can define both static and instance constants (final)
An abstract class can define instance variables
Modification of existing abstract class code has ripple effects on extending classes (implementation maintenance)
Adding a new method to an abstract class has no ripple effect on extending classes
An abstract class can implement an interface
Abstract classes can implement private and protected methods

Abstract classes should be used for (partial) implementation.
They can be a mean to restrain the way API contracts should be implemented.


@Javin on e more short example I want to add ..

7 down vote

I will give you an example first :

public interface LoginAuth{
public String encryptPassword(String pass);
public void checkDBforUser();

Now suppose you have 3 databases in your application then each and every implementation for that db need to define the above 2 methods where encryptPassword() is not dependent on db. Means

public class DBMySQL implements LoginAuth{
// Need to implement both method
public class DBOracle implements LoginAuth{
// Need to implement both method
public class DBAbc implements LoginAuth{
// Need to implement both method

But here in our scenario encryptPassword is not db dependent. So we can use below approach :

public abstract class LoginAuth{
public String encryptPassword(String pass){
//Implement default behavior here
public void checkDBforUser();

Now in our child class, we need to define only one method which is db dependent.

I tried my best and Hope this will clear your doubts.

..:: PchiwaN ::.. said...

Great post, very clear and well explained use scenarios and examples. Thanks a bunch dude!

Unknown said...

Fantastic difference !!! A clear distinction between abstract class and interface from design perspective.

Anonymous said...

This is one of the good OOP Interview question for Java developers, more important for beginners.

Unknown said...

"Programming for interfaces than implementation is also one of the useful Object oriented design principle which suggests benefit of using interface as argument to function, return type etc."

I didn't actually get this. Can you please explain a bit on this?

Anonymous said...

what is the difference between abstract class and interface in java8?

JavaCodeGeek said...

Can you please update this post according to java8 implementation

javin paul said...

Hello Abhishek, yes, will do but meanwhile you can check my other post on Java 8 differences between abstract class and interface . That might help you.

Post a Comment