Probably the most popular question during Java technical interviews is “What’s the difference between abstract classes and interfaces”. In my own three year old book I’ve offered the following answer:
“An abstract class may contain code in method bodies, which is not allowed in an interface.With abstract classes you have to inherit your class from the abstract one because Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.”
But starting from Java 8 this answer is wrong. This is how I’d answered it now:
1. The short answer: “Abstract classes can implement state in member variables, but interfaces can’t. You can extend from one abstract class, but implement multiple interfaces.”
2. The long one: “Both abstract classes and interfaces allow you to implement common static methods while leaving the implementation of some methods to other classes. Abstract classes can also have instance-specific methods and they enforce vertical inheritance hierarchy. Interfaces can’t have instance methods, but they don’t enforce any class hierarchy, so your class can extend any other class while implementing multiple interfaces.“
So abstract classes and interfaces have subtle differences now, which are good to recognize anyway. You can find more details on this subject in the draft of Chapter 5 of my upcoming Java for Kids book.
When I answered this question during my last (and successful) job interview I gave the ‘old’ answer first, and after that I mentioned Java8 improvement with default method – You wanna show to the interviewer that you’re technically up-to-date, not that you’re ahead of him/her!
Java training is a general purpose programming language, it highlights all of the key differences. If an abstract class implements an interface, it does not hold to actually define the interface’s methods. However, a particular class must implement all interface methods that are not implemented by its parent class. It is a component of the Java technology concept of interfaces.
My try: an interface defines some contract and may not have state (fields); abstract classes may both define some contract and provide its partial implementation; abstract classes can hold some state (fields) to support this partial implementation.
This definition should work across all Java versions 🙂
Actually, the absense of static methods in pre-8 Java was a strange ommision, while nothing in jvm, bytecode instructions or class file format prevents them.
Nice explanation about the differences of Abstract class and Interface in java.
it is very useful post.
thanks for sharing this article.
Abstract classes can have a constructor because the constructor does not define a method signature that must be matched inherited by child classes. It’s the only method that doesn’t require that same signature on child implementations