I can't think of a better name for the question, but I hope that an example will make this simpler.
Suppose I create my own custom List
(it is irrelevant what it does):
static class MyList<E> extends AbstractList<E> {
@Override
public E get(int index) {
return null;
}
@Override
public int size() {
return 0;
}
}
I can now create an instance of it and call a different method then the one I have overridden:
MyList<String> myList = new MyList<>();
myList.iterator();
Of course, iterator
should use the get
method that I have declared, but is this a guarantee? Does it mean that iterator
can not change in a way that it does not use get
at all?
For a simpler example, you can think about addAll
. Suppose that my MyList
also overrides add
:
@Override
public boolean add(E e) {
return super.add(e); // irrelevant what it does
}
and then I can do : myList.addAll(someOtherCollection)
. addAll
could be implemented a simple:
for(E e: someOtherCollection) {
// use add that I have overridden
}
but at the same time, the implementation can change, and not use a loop at all (like ArrayList
for example).
Granted, both iterator
and addAll
have some mentions in the documentation like:
This implementation returns a straightforward implementation of the iterator interface, relying on the backing list's size(), get(int), and remove(int) methods.
and
This implementation iterates over the specified collection, and adds each object returned by the iterator to this collection, in turn.
So does that mean that this can NOT change and is treated as "specification"? Now that I wrote this long question and re-read it, the answer might be an obvious "yes".
The Javadoc for AbstractList (JDK21) says
The documentation for each non-abstract method in this class describes its implementation in detail.
So yes, this is part of the specification.