When To Use Abstract Classes And Interfaces
Posted July 25, 2022 by Rohith ‐ 1 min read
It is not only important to understand the differences between abstract class and interfaces, but also understanding when to use them will help you in developing and delivering maintainable software.
When To Use Abstract Classes
You should prefer the abstract class in the following scenarios,
You want to share code among multiple closely related classes. The classes that extend the abstract class can have many common methods or fields, or they require non-public access modifiers inside them. You want to use non-static or/and non-final fields, which enables us to define methods that can access and modify the state of the object to which they belong.
When To Use Interfaces
On the other hand, you should prefer interfaces for these scenarios
You expect that several unrelated classes are going to implement your interface (e.g., comparable interface can be implemented by many unrelated classes). You specify the behavior of a particular data type, but it does not matter how the implementer implements that.You want to use the concept of multiple inheritance in your application.