Difference between an abstract class and an interface and when should you use them?An abstract has one or more abstract methods apart from concrete methods. All the abstract methods must be overridden by its subclasses. An abstract may not have even a single abstract methods. Whereas an interface contains only method signatures.
By default all the methods in an interface are public and abstract. Where as in abstract class, the access specifiers are to be used as and when the application demands. The interface implementing classes must provide all the method definitions that are available in the interface.
Abstract class definition starts with key word ‘abstract’, where as interface definition starts with the key word ‘interface’.
An interface can extend any number of interfaces, where as an abstract class can extend only one abstract class.
All the variables in the interface are public static by default, where as an abstract class can have instance variables.
In a situation where a class needs to extend another class, that class can also implement one or more interfaces to take complete advantage of them. In another situation where a class needs to implement all the methods, then interfaces are utilized.
It is not mandatory to override a concrete method of an abstract class. In situation where few methods definition to be made as and when required by taking the advantage of inheritance, utilize an abstract class.
When the behaviour of a sub type is not very different from its super type then the choice of an abstract class is a better option. However, if the implementations vary largely then an interface should be used.
|