gpt4 book ai didi

Java 无法访问内部类中的 protected 变量

转载 作者:行者123 更新时间:2023-11-29 03:23:19 27 4
gpt4 key购买 nike

这是我的代码

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 的 protected 变量,但是当尝试从子类 MyIterator 访问它时,尽管该变量受到保护,但它不起作用。

为什么它不起作用,我该如何修复它????

非常感谢!!!

最佳答案

this 总是 引用当前对象。因此,在 MyIterator 中,this 指的是 MyIterator 实例,而不是列表。

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

关于Java 无法访问内部类中的 protected 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22436050/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com