Abstract classes are meant to be inherited from, and when one class inherits from another it means that there is a strong relationship between the 2 classes.Abstract class may provide some default implementation code.
With an interface on the other hand, the relationship between the interface itself and the class implementing the interface is not necessarily strong
abstract class would be more appropriate when there is a strong relationship between the abstract class and the classes that will derive from it. This is because an abstract class is very closely linked to inheritance, which implies a strong relationship.
But, with interfaces there need not be a strong relationship between the interface and the classes that implement the interface.
When to use abstract class and interface in Java?
Here are some guidelines on when to use an abstract class and when to use interfaces in Java:
- An abstract class is good if you think you will plan on using inheritance since it provides a common base class implementation to derived classes.
- An abstract class is also good if you want to be able to declare non-public members. In an interface, all methods must be public.
- If you think you will need to add methods in the future, then an abstract class is a better choice. Because if you add new method headings to an interface, then all of the classes that already implement that interface will have to be changed to implement the new methods. That can be quite a hassle.
- Interfaces are a good choice when you think that the API will not change for a while.
- Interfaces are also good when you want to have something similar to multiple inheritance, since you can implement multiple interfaces.
No comments:
Post a Comment