I am preparing myself for Java certification test and I have found an interesting question related to the execution of Java static blocks. I have spent a lot of time reading about this topic, but I didn't find the answer I was looking for.
I know that static blocks are executed when the class is loaded into JVM or when the main method is invoked, but...
package oneClassTasks;
class Parent {
static int age;
}
class Child extends Parent {
static {
age = 5;
System.out.println("child's static block");
}
}
public class XXX {
public static void main(String args[]) {
System.out.println("Child age is : "+ Child.age);
}
}
The output is:
Child age is : 0
If I include verbose output with -verbose:class
, then the output is:
...
[Loaded java.security.BasicPermissionCollection from C:\Program Files\Java\jre1.8.0_161\lib\rt.jar]
[Loaded oneClassTasks.XXX from file:/D:/temp/bin/]
[Loaded sun.launcher.LauncherHelper$FXHelper from C:\Program Files\Java\jre1.8.0_161\lib\rt.jar]
[Loaded java.lang.Class$MethodArray from C:\Program Files\Java\jre1.8.0_161\lib\rt.jar]
[Loaded java.lang.Void from C:\Program Files\Java\jre1.8.0_161\lib\rt.jar]
[Loaded oneClassTasks.Parent from file:/D:/temp/bin/]
[Loaded oneClassTasks.Child from file:/D:/temp/bin/]
Child age is : 0
[Loaded java.lang.Shutdown from C:\Program Files\Java\jre1.8.0_161\lib\rt.jar]
[Loaded java.lang.Shutdown$Lock from C:\Program Files\Java\jre1.8.0_161\lib\rt.jar]
We can see here that Child class is loaded into JVM.
Can someone explain why the static block from Child
class is not executed?