UrsinusTheStrong
UrsinusTheStrong

Reputation: 1207

Static block is not getting executed in case of anonymous objects

Why doesn't a static block in the class get executed when I don't create a reference variable for an object (anonymous) of that class?

For example, let us consider this simple class:

public class StaticDemo {

    private static int x;

    public static void display(){
        System.out.println("Static Method: x = "+x);
    }

    static {
        System.out.println("Static Block inside class");
    }

    public StaticDemo(){
        System.out.println("Object created.");
    }

}

Another class using it:

public class UseStaticDemo {
    public static void main(String[] args) {
        StaticDemo Obj = new StaticDemo();
        Obj.display();

        System.out.println("------------");

        new StaticDemo().display();
    }
}

Output:

Static Block inside class
Object created.
Static Method: x = 0
------------
Object created.
Static Method: x = 0

Upvotes: 0

Views: 73

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280181

A static initializer block only runs once, when the class is loaded and initialized.

Also, static methods have absolutely no relation to any instances. Doing

new StaticDemo().display();

is pointless and unclear.

Upvotes: 5

Related Questions