【问题标题】:Java cannot access a protected variable in inner classJava 无法访问内部类中的受保护变量
【发布时间】:2014-04-21 13:51:03
【问题描述】:

这是我的代码

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 访问它时,尽管该变量受到保护,但它不起作用。

为什么它不起作用,我能做些什么来修复它????

非常感谢!!!

【问题讨论】:

  • 那不是子类,而是一个内部类。
  • 现在是 2014 年,您正在编写非泛型代码...
  • @Darkhogg 哦!仿制药被引入已经有十年了:)
  • 我知道,我知道。不要评判我。我会使用泛型,但我的课程结构有点奇怪。

标签: java oop subclass protected


【解决方案1】:

this always 指的是当前对象。所以,在MyIterator 内部,this 指的是MyIterator 实例,而不是列表。

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

【讨论】:

  • protected 用于允许 子类 访问成员。您在这里没有任何子类,只有一个 inner 类。子类是可以扩展您的 LinkedUserList 的类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-21
  • 1970-01-01
  • 2020-11-02
  • 2014-05-14
  • 2011-05-24
  • 2023-01-13
  • 2019-07-12
相关资源
最近更新 更多