Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should an interface that is inherited from base-class be implemented explicitly in subclass?

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?

like image 213
Mnementh Avatar asked Dec 12 '08 13:12

Mnementh


People also ask

Does a subclass inherit interface?

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.

Are better in situations in which one does not have to inherit implementation from a base class?

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.

Can a base class implement an interface?

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.

When should I use an interface and when should I use a base class?

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.


1 Answers

Avoid redundancy. Use method 2.

Use @Override for overrides.

like image 192
krosenvold Avatar answered Oct 19 '22 05:10

krosenvold