JVM如何初始化一个类

初始化一个类

经典案例

public class Singleton {

    private static Singleton instance = new Singleton();

    public static Singleton getInstance() {
        return instance;
    }

    public static int x = 0;
    public static int y;

    private Singleton() {
        x++;
        y++;
    }

    public static void main(String[] args) {
        Singleton singleton = getInstance();
        System.out.println(x); // 0
        System.out.println(y); // 1
    }
}

public class Singleton2 {

    public static int x = 0;
    public static int y;

    private static Singleton2 instance = new Singleton2();

    public static Singleton2 getInstance() {
        return instance;
    }

    private Singleton2() {
        x++;
        y++;
    }

    public static void main(String[] args) {
        Singleton2 singleton = getInstance();
        System.out.println(x); // 1
        System.out.println(y); // 1
    }
}

更多
https://www.freesion.com/article/49021063734/

posted @ 2021-07-19 21:18  vaen  阅读(40)  评论(0)    收藏  举报