Overriding the same method twice from the same class
I figured out how the iterator () method works with the ArrayList class. In the ArrayList class, I found the iterator () method, overridden twice from the same AbstractList class.
public Iterator<E> iterator() {
return new Itr(); // Itr is an inner private class of
// ArrayList which
// implements Iterator interface .
}
public Iterator<E> iterator() {
return listIterator();
}
But how is this possible? There should be an error here that is already defined. I am embarrassed.
source to share
The first iterator()
method you see is for a class ArrayList
, but the second is not.
It belongs to a class SubList
that is an inner class ArrayList
:
private class SubList extends AbstractList<E> implements RandomAccess {
...
public Iterator<E> iterator() {
return listIterator();
}
...
}
Therefore, it is not overridden twice by the same class. Each class overrides it once.
source to share
Overriding the same method twice from the same class is not allowed. In your case, these are two different classes, namely:
public class ArrayList<E> extends AbstractList<E>
private class SubList extends AbstractList<E> implements RandomAccess
and the latter is an inner class of the former, so both can have the same method with the same signature.
source to share