简体   繁体   English

Java无法访问内部类中的受保护变量

[英]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. 问题是我有一个称为head的受保护变量,但是当尝试从MyIterator子类访问它时,尽管该变量受到保护,但它仍然无法工作。

Why is it not working and what can i do about fixing it???? 为什么它不起作用,我该怎么办?

Many Thanks!!! 非常感谢!!!

this always refers to the current object. this 总是指当前对象。 So, inside MyIterator , this refers to the MyIterator instance, not the list. 因此,在MyIterator内部, this是指MyIterator实例,而不是列表。

You need to use LinkedUserList.this.head , or simply head , to access the head member of the outer class. 您需要使用LinkedUserList.this.head或仅使用head来访问外部类的head成员。 Note that inner classes can access private members of their outer class, so head doesn't need to be protected . 请注意,内部类可以访问其外部类的私有成员,因此head不需要protected It can be private . 它可以是private

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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