Only super class is initialized even though static

2019-09-05 23:00发布

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.

3条回答
看我几分像从前
2楼-- · 2019-09-05 23:24

As shown above, when I run the Superclass/Subclass example, on calling Subclass.INIT_TIME, both the Superclass and Subclass static initializers are getting invoked.

But here it is said that only "Initializing Superclass" will be printed. Can someone clarify?

查看更多
劳资没心,怎么记你
3楼-- · 2019-09-05 23:34

I think the point is that in a situation like this:

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");
    }
}

This code:

long time = Subclass.INIT_TIME;

is actually compiled to:

long time = Superclass.INIT_TIME;

and only "Initializing Superclass" will be printed, even though the source code referred to Subclass.

查看更多
Rolldiameter
4楼-- · 2019-09-05 23:45

An example:

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;
}

Client:

int test = B.nA;

The JVM will initialize only Class A. Not B nor C.

查看更多
登录 后发表回答