Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

关于java static 初始化的问题

有如下代码:

public class StaticTest {


    public static void main(String[] args) {
//        Class<?>  demoClass =  Demo.class;
        String s = Demo.demo;
//        Ok o = Demo.o;
    }
    private static class Ojbk {
        static {
            System.out.println("ojbk  static");
        }
    }
    private static class Ok {
        static {
            System.out.println("ok static");
        }
    }
    private static class Demo{
        static {
            System.out.println("demo static");
        }
        private final static String demo = "123";
        private final static Ok o = new Ok();

        private final static Ojbk ojbk = new Ojbk();

    }
}

对于运行结果有点疑惑:
当在main方法中只调用Demo.demo的时候,okojbk都不会初始化,这很好理解,Demo.demo在准备阶段就已经和Demo.class无关了,所以不会触发Demo的初始化。

从运行结果来看,o,ojbk 是在Demo初始化的时候才完成自身的初始化的,那么在准备阶段,o,ojbk 做了什么?如果是static,那么是赋值为null,final static 是否也是赋值为null,有具体的参考资料吗?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

四个类只有StaticTest加载了,Demo,Ok,OJBK都没有加载,所以什么都没做


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...