My question is, if an interface that is implemented implicitly by extending a class that already implements it, should be explicitly implemented by the class, if the class wants to advertise the fact, that it fulfills the contract of that interface.
For instance, if you want to write a class, that fulfills the contract of the interface java.util.List
. You implement this, extending the class java.util.AbstractList
, that already implements the interface List
. Do you explicitly declare, that you implement List?
public class MyList extends AbstractList implements List
Or do you save typing by using the implicit way?
public class MyList extends AbstractList
Which way is considered better style? What reasons do you have to prefer one way or another? In which situations you would prefer way 1 or way 2?
No. An interface defines how a class should look like (as a bare minimum). Whether you implement this in a base class or in the lowest subclass doesn't matter.
Interfaces are better in situations in which you do not have to inherit implementation from a base class. Interfaces are useful when you cannot use class inheritance. For example, structures cannot inherit from classes, but they can implement interfaces.
A base class can also implement interface members by using virtual members. In that case, a derived class can change the interface behavior by overriding the virtual members.
My rule of thumb: If you want to provide some common functionality accessible to a subset of classes, use a base class. If you want to define the expected behavior of of a subset of classes, use an interface.
Avoid redundancy. Use method 2.
Use @Override for overrides.
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