Question :
Consider the following code :
class Super { static String ID = "QBANK"; } class Sub extends Super{ static { System.out.print("In Sub"); } } public class Test{ public static void main(String[] args){ System.out.println(Sub.ID); } }
What will be the output when class Test is run ?
A. I t will print In Sub and QBANK.
B. I t will print QBANK.
C. Depends on the implementation of JVM.
D. It will not even compile.
E. None of the above.
Answer
Answer is option B.
Explanation
It would look like the program would print "In sub" followed by QBANK and the option would be A but it is not.
A class is initialized only when it's content (variables/methods) which are not inherited gets referenced. Not otherwise.
From JLS 12.4.1:
From JLS 12.4.1:
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
- T is a class and an instance of T is created.
- T is a class and a static method declared by T is invoked.
- A static field declared by T is assigned.
- A static field declared by T is used and the field is not a constant variable (§4.12.4).
- T is a top-level class, and an assert statement (§14.10) lexically nested within T is executed.