繁体   English   中英

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

[英]Java cannot access a protected variable in inner class

这是我的代码

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...
    }
}

问题是我有一个称为head的受保护变量,但是当尝试从MyIterator子类访问它时,尽管该变量受到保护,但它仍然无法工作。

为什么它不起作用,我该怎么办?

非常感谢!!!

this 总是指当前对象。 因此,在MyIterator内部, this是指MyIterator实例,而不是列表。

您需要使用LinkedUserList.this.head或仅使用head来访问外部类的head成员。 请注意,内部类可以访问其外部类的私有成员,因此head不需要protected 它可以是private

暂无
暂无

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

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