Java无法访问内部类中的受保护变量
这是我的密码Java无法访问内部类中的受保护变量,java,oop,subclass,protected,Java,Oop,Subclass,Protected,这是我的密码 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;
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访问它时,尽管该变量受到保护,但它不起作用
为什么它不工作,我能做些什么来修复它
非常感谢
此
始终引用当前对象。因此,在MyIterator
中,这个
引用的是MyIterator
实例,而不是列表
您需要使用
LinkedUserList.this.head
,或者简单地使用head
,来访问外部类的head
成员。请注意,内部类可以访问其外部类的私有成员,因此head
不需要受到保护。它可以是private
此
始终引用当前对象。因此,在MyIterator
中,这个
引用的是MyIterator
实例,而不是列表
您需要使用LinkedUserList.this.head
,或者简单地使用head
,来访问外部类的head
成员。请注意,内部类可以访问其外部类的私有成员,因此head
不需要受到保护。它可以是private
,它不是子类,而是一个内部类。2014年,你正在编写非泛型代码…@Darkhogg哦!自从引入仿制药以来,这已经有十年了:)我知道,我知道。不要评判我。我会使用泛型,但我的课程结构有点奇怪。那不是子类,而是一个内部类。2014年,你在写非泛型代码…@Darkhogg-Oh!自从引入仿制药以来,这已经有十年了:)我知道,我知道。不要评判我。我会使用泛型,但我的课程结构有点奇怪。protected用于允许子类访问成员。这里没有任何子类,只有一个内部类。子类是扩展LinkedUserList的类。protected用于允许子类访问成员。这里没有任何子类,只有一个内部类。子类是扩展LinkedUserList的类。