Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing parent class static field using child class name doesn't load the child class?

class A {
    static int super_var = 1;
    static {
        System.out.println("super");
    }
}

class B extends A {
    static int sub_var = 2;
    static {
        System.out.println("sub");
    }    
}
public class Demo{
    public static void main(String []args){
        System.out.println(B.super_var);
    }
}

outputs are :

super
1

this means that the child class not going to load or any other thing? how is it works?

like image 934
Kalhan.Toress Avatar asked Mar 22 '14 19:03

Kalhan.Toress


1 Answers

When you access the static fields of a super class on subclass reference, only the class that declares the field will be loaded and initialized, in this case it is A. This is specified in JLS §12.4.1 - When Initialization Occurs:

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.

Emphasis mine.

So in your code, class B would not even be initialized, and hence its static block would not be executed.

like image 189
Rohit Jain Avatar answered Sep 20 '22 00:09

Rohit Jain