當我使用匿名內部類創建節點時。當我打印所有的鍵,他們打印爲0,而不是我在匿名類聲明中分配的值。難道我做錯了什麼?這裏是我的代碼:匿名內部類成員在java中不可訪問
public class LinkedListTest {
Node head;
public void addInOrder(final int value) {
if (head == null) {
head = new Node() {
int key = value;
};
}
else if(head.key > value) {
final Node temp = head;
head = new Node() {
int key = value;
Node next = temp;
};
}
else {
Node theNode = head;
while(theNode.key < value) {
if (theNode.next == null) {
theNode.next = new Node() {
int key = value;
};
return;
}
else if(theNode.next.key > value) {
final Node temp = theNode.next;
theNode.next = new Node() {
int key = value;
Node next = temp;
};
return;
}
theNode = theNode.next;
}
}
}
這是我爲我的節點類聲明:
class Node {
int key;
Node next;
}
這是我的打印方法:
public void printAll(Node hasNode) {
if (hasNode != null) {
System.out.println(hasNode.key);
if (hasNode.next != null) {
printAll(hasNode.next);
}
}
}
安迪打敗了我幾秒鐘:-),但是,這就是發生了什麼。匿名子類中的'int key = value;'聲明並初始化匿名子類中的實例變量,該實例變量覆蓋'Node'中相同名稱的字段。 – blm
我明白了,但是如果我賦值給它們的值字段,匿名內部類的最後一點是不能在它們聲明的範圍之外訪問的?我認爲在這種情況下「陰影」會起作用。 感謝您的反饋! –
匿名內部類有很多用途,不涉及聲明相同名稱的成員變量。但是,在匿名內部類中聲明的任何成員變量或非重寫方法幾乎都是不可訪問的,因爲您只需引用「Node」,而不是「NodeList」的特定子類LinkedListTest $ 1。 –