Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any benefit in implementing a interface in a subclass even though the superclass implements the same interface

Tags:

java

oop

When I was seeing the declaration of ArrayList

class ArrayList<E> extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable

which implements List interface even though ArrayList's superclass AbstractList implements the same List interface.

abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>

Similar declarations can be found on HashMap, LinkedHashMap declarations also.

enter image description here

In the declaration of LinkedHashMap, it implements Map interface only and not the other interfaces implemented by its superclass HashMap.

So there might be some benefits of having such declarations.

like image 527
Charles Green Way Avatar asked Apr 05 '13 12:04

Charles Green Way


People also ask

Why would you define an interface and not a superclass?

If you only want to inherit method signatures (name, arguments, return type) in the subclasses, use an interface, but if you also want to inherit implementation code, use a superclass.

Can multiple classes implement the same interface in Java?

Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.

What was the advantage of implementing the interface?

Implementing an interface enforces your class to be bound to the contract (by providing the appropriate members). Consequently, everything that relies on that contract (a method that relies on the functionality specified by the interface to be provided by your object) can work with your object too.

Why We Need interface instead of class and what we are achieving from interface?

Interface is nothing but its a guide line for the new implementation it provides some instructions for new implementation and categorize the functionality of the object . In details like if we create an interface then we create an instruction for the implementation .


2 Answers

There are no functional benefits to declaring them again, it does not affect the behavior in any way.

I guess it's only added to make it clearer which interfaces are implemented.

like image 91
Keppil Avatar answered Nov 15 '22 18:11

Keppil


This is done for documentation purposes only, to make it immediately clear to the user of the class which interfaces the class implements.

The redundant implements clause makes no difference to the compiler.

like image 20
NPE Avatar answered Nov 15 '22 18:11

NPE