简体   繁体   中英

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 .

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.

Overriding the same method twice from 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, that's why both can have same method with same signature.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM