关于内部类的初始化趣事

关于内部类初始化

今天在写代码时,碰到再内部类初始化过程中调用外部类变量的情况,代码如下:

class TestNode{
    class Node{
        Node next;
        Node(){
            next = nil;
        }
    }
    Node nil, head;

    public TestNode() {
        nil = new Node();
        head = new Node();
    }

    public void printInfo() {
        System.out.println("nil is : " + nil);
        System.out.println("nil.next is : " + nil.next);
        System.out.println("head is : " + head);
        System.out.println("head.next is : " + head.next);
    }
}

在这段代码中,内部类Node在构造函数中调用了外部类TestNode的Node变量nil,预先是想nil的next值会被赋值为nil本身,但是运行printInfo()时得到了下面的结果:

public class TestMain {
    public static void main(String[] args) {
        TestNode testNode = new TestNode();
        testNode.printInfo();
    }

}
nil is : TestNode$Node@232204a1
nil.next is : null
head is : TestNode$Node@4aa298b7
head.next is : TestNode$Node@232204a1

可以看到,nil是在构造函数调用之后才得到新Node的地址,所以以后出现这种循环赋值的时候要特别注意。

posted @ 2020-11-01 14:47  nohack7  阅读(50)  评论(0)    收藏  举报