簡體   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