在Class本身内创建一个实例

时间:2012-06-25 15:10:45

标签: java instantiation

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


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");
    }
}

1 个答案:

答案 0 :(得分: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)