简体   繁体   中英

Java cannot access a protected variable in inner class

Here is my code

class LinkedUserList implements Iterable{
    protected LinkedListElement head = null;    /*Stores the first element of the list */
    private LinkedListElement tail = null;    /*Stores the last element of the list */
    public int size = 0;                      /* Stores the number of items in the list */

//Some methods....
//...

    public Iterator iterator() {
        return new MyIterator();
    }

    public class MyIterator implements Iterator {
        LinkedListElement current;

        public MyIterator(){
            current = this.head; //DOSEN'T WORK!!!
        }

        public boolean hasNext() {
            return current.next != null;
        }

        public User next() {
            current = current.next;
            return current.data;
        }
        public void remove() {
            throw new UnsupportedOperationException("The following linked list does not support removal of items");
        }
    }
private class LinkedListElement {
    //some methods...
    }
}

The problem is that I have a protected variable called head, but when trying to access it from a subclass MyIterator, then it does not work, despite the variable being protected.

Why is it not working and what can i do about fixing it????

Many Thanks!!!

this always refers to the current object. So, inside MyIterator , this refers to the MyIterator instance, not the list.

You need to use LinkedUserList.this.head , or simply head , to access the head member of the outer class. Note that inner classes can access private members of their outer class, so head doesn't need to be protected . It can be private .

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