What's going on when the assignment statement executed at Line 4, does compiler ignore the new operator and keep the foo variable being null or something else happen to handle this awkward moment?
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");
}
}
The compiler doesn't do anything special here. It could warn you that this won't work, but that is hard to determine.
You will get a 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();
}
}
prints
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With