Difference between abstract class and Interface
abstract class vs Interface:
What is the difference between abstract class and interface? This is most probably one of the most asked questions regarding Java which have proved to be quite confusing for beginners and professionals alike. Thus this article seeks to provide an answer to that question which has been sought by many over time.
What is abstract class?
Abstract class, also known as an abstract superclass is a class created as a master structure but which also cannot be instantiated. It can only be sub-classed with their own variations which only allows other classes to inherit from it. An abstract class can contain internal member variables as well as basic behaviour in the form of methods that have been coded.
What is interface?
While an interface is not a class, it defines a set of methods but it does not implement them as it does not contain any code to do so. A Java interface should be implemented using keyword “implements” and it is also utilized to define hierarchies for all subclasses.
What is the difference between Interface and abstract class?
While an abstract class is defined as a class, interface is not. It is a different entity which is defined as interface. Also, while an abstract class is only used when there is a “is-a” type of relationship between the classes, it is possible to implement an interface by classes that are not related to one another. Also, while in abstract class, more than one class cannot be extended, in interface, it is possible to implement more than one interface which in turn creates a form of multiple inheritance.
While interface only defines a set of methods and it cannot implement them as a result of having no codes, abstract classes are capable of implementing methods. While abstract class defines only a very few or sometimes none of the methods at all,
interface defines all the methods. Also, while it is possible for an abstract class to contain internal member variables and basic behaviour in the form of methods that have been coded, an interface does not possess either of those things.
Also, while abstract classes are required to have subclasses, interfaces are required to have implementations by other classes in order to be useful. Also abstract classes are known to function faster whereas interfaces tend to be slow as a result of requiring extra indirection to find a corresponding method in the actual class.
Interface is considered to be absolutely abstract and also, it cannot be instantiated. An abstract class too cannot be instantiated and yet, it can be invoked if a main exists.