Execution of child class' static block derived from abstract class

ANSHUL KUMAR :
public class Test15 {
    public static void main(String[] args) {
        System.out.println(B.x);
    }
}

abstract class A { 
    static int x=99;

    A() {
        System.out.println("A DC");
    }

    static {
        System.out.println("A SB");
    }
}

class B extends A {
    static {
        System.out.println("B Sb");
    }
}

Why in the above program the child class static block is not executed ?

Eran :

x is a static variable of class A, so even though you access it via B.x, there's no need to initialize class B. Therefore, class B's static initializer is not executed.

Here's the relevant JLS 12.4.1 quote:

A reference to a static field (§8.3.1.1) causes initialization of only the class or interface that actually declares it, even though it might be referred to through the name of a subclass, a subinterface, or a class that implements an interface.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=130280&siteId=1