Reputation: 475
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?
Upvotes: 7
Views: 4028
Reputation: 15446
The Iterable
interface was introduced later since 1.5
. So, earlier to this version only java.util.Collection
subclasses used to implement iterator()
.
Later iterator()
was made standard by introducing Iterable
interface such that any Class which can iterated can implement this interface.
After introducing Iterable
interface, the Collection
interface was also made to extend Iterable
interface such that Collection
interface also implements the standard one.
For Ex,
java.sql.SQLException
also implements IterableUpvotes: 0
Reputation: 236004
The Collection
interface extends Iterable
. An abstract superclass implements the methods common to several classes, in the case of lists, it's AbstractList
, with each concrete class (say, ArrayList
or LinkedList
) providing the specific implementation details.
In fact, as you've guessed, inheritance is used for reducing code duplication. But precisely because of that, all the subclasses will contain the same operations defined in the superclasses, the implementation details common to several classes will appear only once in the class hierarchy at the abstract class level, and they are not "defined" again in the subclasses - only the parts that change are redefined in concrete subclasses.
Upvotes: 1
Reputation: 30022
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.
Upvotes: 1
Reputation: 4169
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."
Upvotes: 5