当我使用匿名内部类创建节点时。当我打印所有的键,他们打印为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。 –