Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding same method twice from same class

I was understanding how iterator() method works with ArrayList class . In ArrayList class I found iterator() method overridden twice from same class AbstractList .

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 of already defined . I am confused .

like image 719
shikhar Avatar asked Jan 26 '26 11:01

shikhar


1 Answers

The first iterator() method you see belongs to the ArrayList class, but the second does not.

It belongs to the SubList class, which is an inner class of 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.

like image 119
Eran Avatar answered Jan 29 '26 01:01

Eran