I stumbled upon 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);
}
}
We are referencing class Sub
as Sub.id
. So i expected the static block in the Sub class to be executed and "In Sub" to be printed but to my surprise it does not. Although variable ID is visible to Sub class from Super class since we are referring to the variable using Sub class I expect it to be loaded first. And if it gets loaded then the static block should get executed.
Since it is not getting printed is it that Sub class is not loaded at all? How is that possible when I am clearly referencing it in my code. I mean how a class could be recognized without getting loaded into the memory? Something I am missing?