0

I am doing some research on JAVA initialization process. Here is a good material for reference: When a class is loaded and initialized in JVM

On this page there is rule says: 3) If Class initialization is triggered due to access of static field, only Class which has declared static field is initialized and it doesn't trigger initialization of super class or sub class even if static field is referenced by Type of Sub Class, Sub Interface or by implementation class of interface.

I really don't understand the idea. If the static field is referenced by Sub class, then this field of course need to create a sub class object or assigned by a Sub class object. So, it definitely triggers Sub class initialization.

What's wrong with my interpretation?


EDIT:

  1. It DOES trigger Super Class static initialization.
  2. If the static field is final, and the static final field is initialized when declaring. Then it will neither load the class nor initialize the class, for this static final field is a compile time constant value. Attention: if the static final field is initialized in static block, then this statement does NOT hold anymore.
4

3 回答 3

3

我认为关键是在这样的情况下:

public class Superclass {
    public static long INIT_TIME = System.currentTimeMillis();

    static {
        System.out.println("Initializing Superclass");
    }
}

public class Subclass extends Superclass {
    static {
        System.out.println("Initializing Subclass");
    }
}

这段代码:

long time = Subclass.INIT_TIME;

实际上编译为:

long time = Superclass.INIT_TIME;

并且只会打印“Initializing Superclass”,即使引用了源代码Subclass

于 2013-04-30T16:34:21.730 回答
0

如上所示,当我运行超类/子类示例时,在调用 Subclass.INIT_TIME 时,超类和子类静态初始化程序都被调用。

但这里据说只会打印“Initializing Superclass”。有人可以澄清吗?

于 2014-11-02T14:54:15.640 回答
0

一个例子:

class A {
   public static int nA = 0;
}

class B extends A {
   public static int nB = 1;
}

class C extends B {
   public static int nC = 2;
}

客户:

int test = B.nA;

JVM 将仅初始化 A 类。而不是 B 或 C。

于 2013-04-30T16:34:31.970 回答