Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an instance within the Class itself

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

like image 981
didxga Avatar asked Mar 11 '26 12:03

didxga


1 Answers

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)
like image 56
Peter Lawrey Avatar answered Mar 14 '26 03:03

Peter Lawrey