[英]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.