6
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?

3
  • I don't understand your question. What output did you expect? Commented Mar 22, 2014 at 19:37
  • 3
    @RohitJain I suppose the static initialiser for B was expected to be called. Commented Mar 22, 2014 at 19:38
  • @boris yes that is what i expected Commented Mar 22, 2014 at 19:42

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Checkout the answer to this question: In what order do static initializer blocks in Java run?

The static block gets called only when a class is accessed (either creating an instance or accessing a member field or static method). However, you access a member of class A only, so there is no reason for class B to be initialized yet. The static initializer of B will be called as soon as you access a member from that class (either a field or static method, or create an instance from class B).

The reason is that class B doesn't need to be initialized until you access one of its members. Because A doesn't know about B (and cannot access it) there's really no reason for B to initialize at that stage.

You will find out that when you access B.sub_var the static initializer of B will be executed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.