InterviewSolution
| 1. |
What is the difference between an interface and an abstract class? When we should prefer the interface over abstract class? |
|
Answer» A class can inherit from both an ABSTRACT class and an interface, but there are some differences. A class can extend only one abstract class while can implement multiple interfaces. An interface cannot have a constructor whereas the abstract class can have constructors which the child classes need to invoke in their constructors. An abstract class may contain fields which may be accessible by child classes to change its state. Interface, on the other hand, can contain only final variables. So, abstract class lets the child class to inherit the state and behavior while the interface is mainly used for implementing a SET of behaviors in a child class. An abstract class should be preferred where there is a direct IS-A relationship between the PARENT and the child. We use abstract class when the different implementations have most of the behaviors common and defined by the abstract class. An interface is preferred while exposing a public API to the CLIENT code and if a class can behave differently in different context. |
|