Frage

This question might be blunder to some of the Java Experts. But I would like to know why we create the objects in a static method like main but not in static block. I understand that its going to create the object unnecessarily if we instantiate in static block and of course if we don't use it further. Are there any other things that are to be noted with this approach ? Can we relate this with Singleton Pattern ?

For example:

public class MyClass {

    static {
        AnotherClass object = new AnotherClass();
            // Do Some operations here with object.
    }
}
War es hilfreich?

Lösung

The main reason is control over when it actually gets executed. The stuff in a static block will get executed the first time that the class is loaded and it's easy to accidentally cause a class to be loaded (for instance by referencing a constant on the class).

Having a static method means that you have complete control over when the method is called (because you have to explicitly call it).

In regards to singletons, the java idiom for eagerly loaded singletons initializes the instance as a static field. This will basically run just the same as a static block.

public class Singleton {
    private static final Singleton instance = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top