简体   繁体   中英

When are static fields initialized in Java?

In this basic implementation of Singleton, when is the new Singleton1() call actually occuring (marked with * ?

public final class Singleton1 {

    private Singleton1() { }

    private static Singleton1 instance = new Singleton1(); // (*) When does this happen?
                                                           //     Before calling getInstance() from the client?

    public static Singleton1 getInstance() {
        return instance;
    }
}

Static fields are populated when the class is first loaded by the JVM (See JLS 12.4 ). So yes, instance will be populated before getInstance() can be called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM