Why doesn't this statement throw a StackOverflowError?

Anthony Raymond :

I just saw this weird piece of code in another question. I thought it would result in a StackOverflowError being thrown, but it does not...

public class Node {
    private Object one;
    private Object two;
    public static Node NIL = new Node(Node.NIL, Node.NIL);

    public Node(Object one, Object two) {
        this.one = one;
        this.two = two;
    }
}

I thought it was going to explode, because of the Node.NIL referencing itself to build.

I can't figure it out why it does not.

Eran :

NIL is a static variable. It is initialized one time, when the class is initialized. When it is initialized, a single Node instance is created. The creation of that Node doesn't trigger creation of any other Node instances, so there is not infinite chain of calls. Passing Node.NIL to the constructor call has the same effect as passing null, since Node.NIL is not yet initialized when the constructor is called. Therefore public static Node NIL = new Node(Node.NIL, Node.NIL); is the same as public static Node NIL = new Node(null, null);.

If, on the other hand, NIL was an instance variable (and wasn't passed as an argument to the Node constructor, since the compiler would have prevented you from passing it to the constructor in that case), it would be initialized every time an instance of Node was created, which would create a new Node instance, whose creation would initialize another NIL instance variable, leading to infinite chain of constructor calls that would end in StackOverflowError.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=423044&siteId=1