static和构造函数初始化顺序


abstract class demo{
    public demo() {}
    protected void a() {
        System.out.println("I am parents!");
    }
}

class demoChild extends demo{
    public demoChild() {
        System.out.println("Begin from here");
        a();
        String a  ="hellp";
    }
    static {
        //static初始化优先于构造函数
        System.out.println("Begin/....");
    }
}

public class Elvis {
    private static final Elvis INSTANCE = new Elvis();
    private Elvis() {}
    public static Elvis getInstance() {
        new demoChild();
        return INSTANCE;
    }
    public static void main(String[] args) {
        (new Elvis()).getInstance();
    }
}

 

结果为:

可以看书static标记的位置初始化时优先于构造函数。

 

posted on 2018-05-21 22:17  __keras  阅读(187)  评论(0编辑  收藏  举报

导航