Why are abstract or interface classes created, or when should we use abstract or interface classes?
An interface is better than a abstract class when you want multiple classes to implement that interface and when you don't have to inherit default behavior.
The main advantages of interface over abstract class is to overcome the occurrence of diamond problem and achieve multiple inheritance. In java there is no solution provided for diamond problem using classes. For this reason multiple inheritance is block using classes in java.
If we are using inheritance then the abstract class can be used because it provides a common base class for derived classes. If we want to declare non-public members then abstract class is a better choice than interface because in an interface all methods must be public.
The fourth difference between abstract class and interface in Java is that abstract classes are slightly faster than the interface because the interface involves a search before calling any overridden method in Java.
Interface is used when you only want to declare which methods and members a class MUST have. Anyone implementing the interface will have to declare and implement the methods listed by the interface.
If you also want to have a default implementation, use abstract class. Any class extending the abstract class will have to implement only its abstract methods and members, and will have some default implementation of the other methods of the abstract class, which you may override or not.
--EDIT - forgot to mention, Earwicker reminded me
Finally, you can implement as many interfaces as you want, but only extend one class (being it abstract or not). Keep that in mind before choosing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With