使用static和final修饰符时的奇怪的Java行为

19 浏览
0 Comments

使用static和final修饰符时的奇怪的Java行为

在我们的团队中,我们发现了一些奇怪的行为,当我们同时使用staticfinal修饰符时。这是我们的测试类:

public class Test {
    public static final Test me = new Test();
    public static final Integer I = 4;
    public static final String S = "abc";
    public Test() {
        System.out.println(I);
        System.out.println(S);
    }
    public static Test getInstance() { return me; }
    public static void main(String[] args) {
        Test.getInstance();
    }
} 

当我们运行main方法时,我们得到的结果是:

null

abc

我可以理解为什么会两次输出null值,因为静态类成员的代码是从上到下执行的。

有人可以解释为什么会发生这种行为吗?

0