简体   繁体   中英

Java interface extends interface in the java.util package

As we know, interfaces can extend interface in the Java. I have a question about this, if interface B extends interface A, B need not implement the methods defined in the A. But in the java.util package, the List interface extends Collection interface, and it implements the Collection method, these methods also just have the method declaration.

Why does it do this, and it there a better practice? Does it make any difference between implementing the method in the sub interface or not?

Overriding a method, besides providing/replacing a method implementation, allows to provide a more specific javadoc, and to narrow the return type.

For instance, Collection.iterator() is specified by:

Returns an iterator over the elements in this collection. There are no guarantees concerning the order in which the elements are returned (unless this collection is an instance of some class that provides a guarantee).

while List.iterator() is specified by

Returns an iterator over the elements in this list in proper sequence.

I don't see any implementation in java.util.List but declarations. Instead the javadocs of List say,

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience.

Interfaces are fully abstract in Java. They can't have any implementation.

Redeclaring a method is not the same as implementing it. And it doesn't make any sense to redeclare a method (if the method signature is exactly same), because the purpose of an interface extending another interface is to add some more-specific method declarations, and not to just redeclare the existing ones.


Edit


As pointed out in @Arham's and @meriton's answer, the purpose of the redeclaration is to respecify the method according to the sub-interface. So, for a client code, accessing the underlying collection, there would be a separate more-specific specification on the redeclared methods than the more-general one in the super-interface.

The interface List do not implement Collections' methods because interfaces just cannot implement methods, they just declare them. An interface is like a 100% abstract class: all the methods must be abstract methods.

Probably your confusion comes from abstract classes that implement interfaces: these classes must not implement interface's methods (despite being allowed to), only the first concrete class must.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM