Inheritance in java collection interfaces

Java collection interfaces have some inheritance relationships. For example, the Collection<T> interface will be extended by Iterable<T> . I checked the source code in the JDK, some methods defined in the base class are repeated in subclasses several times. For example: Interable<T> interface defines the Iterator<E> iterator(); But the Collection<E> and List<T> interface also contains the same method. In my understanding, since inheritance is used to reduce duplication, why should we define the same method in subclasses?

+7
source share
4 answers

See java.util.List

"The List interface contains additional conditions, in addition to those specified in the Collection interface, in the contracts of the iterator methods, add, remove, equals and hashCode. Declarations for other inherited methods are also included here for convenience."

+5
source

Collection came out in version 1.2, but Iterable came out after that in version 1.5 to allow for-loops compression, so I think it was a case of keeping the Collection and Javadocs interface the same way between releases. But you're right, there is no reason why you cannot remove the iterator() method from Collection , it will still compile.

+1
source

The Collection interface extends Iterable . An abstract superclass implements methods common to several classes, in the case of lists it has an AbstractList with each specific class (say, ArrayList or LinkedList ), providing specific implementation details.

In fact, you guessed it, inheritance is used to reduce code duplication. But precisely because of this, all subclasses will contain the same operations that are defined in superclasses, implementation details common to several classes will be displayed only once in the class hierarchy at the abstract class level, and they are not yet “defined” into subclasses - only changes that change are redefined in specific subclasses.

+1
source

The Iterable interface was introduced later since 1.5 . Thus, previously for this version, only java.util.Collection subclasses were used to implement iterator() .

iterator() later became standard by introducing an Iterable interface, so that any class that can repeat can implement this interface.

After introducing the Iterable interface, the Collection interface was also decrypted to extend the Iterable interface, so the Collection interface also implements the standard one.

For Ex,

  • java.sql.SQLException also implements Iterable
0
source

All Articles