3

当赋值语句在 处执行时发生了什么Line 4,编译器是否忽略new operator并保持foo变量为 null 或者发生其他事情来处理这个尴尬的时刻?


public class Foo {
 // creating an instance before its constructor has been invoked, suppose the "initializing"  
 // gets printed in constructor as a result of the next line, of course it will not print it
    private  Foo foo = new Foo();//Line 4

    public Foo() {
        System.out.println("initializing");
    }
}

4

1 回答 1

4

编译器在这里没有做任何特别的事情。它可能会警告您这不起作用,但这很难确定。

你会得到一个 StackOverflowError。

public class Foo {
    private  Foo foo = new Foo();//Line 4

    public Foo() {
        System.out.println("initializing");
    }

    public static void main(String... args) {
        Foo foo = new Foo();
    }
}

印刷

Exception in thread "main" java.lang.StackOverflowError
    at Foo.<init>(Foo.java:9)
    at Foo.<init>(Foo.java:7)
    at Foo.<init>(Foo.java:7)
    .. many deleted ...
    at Foo.<init>(Foo.java:7)
    at Foo.<init>(Foo.java:7)
于 2012-06-25T15:13:00.097 回答