Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance in java collection interfaces

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

like image 795
frank.liu Avatar asked Jul 16 '12 13:07

frank.liu


2 Answers

See in java.util.List

"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."

like image 112
Nailgun Avatar answered Sep 28 '22 07:09

Nailgun


Collection came out in release 1.2, but Iterable came out afterwards in release 1.5 to allow for concise for-loops, so I think it was a case of keeping the Collection interface and the Javadocs the same between releases. But you are correct, there is no reason you couldn't remove the iterator() method from Collection, everything would still compile.

like image 38
Garrett Hall Avatar answered Sep 28 '22 07:09

Garrett Hall