Search code examples
javastaticconstructorstatic-initialization

Constructors called due to static initialization


I am going through Thinking in Java by Bruce Eckel 4th Edition. In the chapter Initialization & Cleanup, page : 189 the first bullet point in the second para mentions:

Even though it doesn't explicitly use the static keyword the constructor is actually a static method.

I have the following piece of code:

class Bar {
    Bar() {
        System.out.println("Bar Creation");
    }
}

class Foo {
    static int x = 10;
    static Bar b = new Bar();

    Foo() {
        System.out.println("Foo Creation");
    }
}

public class Test { 
    public static void main(String[] args) {
        System.out.println(Foo.x);
    }
}

If what it says is true The constructor for Foo should have been called. I don't see that happening with the following piece of code.

The output is:

Bar Creation
10

Can someone clarify what does it mean?

I have tried my best to quote the book. I don't think the parts previous to that statement or after that have much relevance to this statement in context of the question.

Thanks,

Gudge


Solution

  • There's no reason for Foo() to be called just because you mentioned the class. Static initializers like static Bar b = new Bar(); are called when the class is loaded; static methods are called by your code.

    I would guess that what the book means is that constructors are like static methods in that the dispatch is static: that is, there is no way to inherit and override a constructor, and a call site for a constructor, or a static method, always refers to some specific class determined at compile time.

    (This staticness of constructors is the motivation for “factory” objects which construct objects in their instance methods.)