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
You saw that Child
class was loaded, but it wasn't initialized.
Accessing Child.age
doesn't cause the initialization of the Child
class, since age
is a member of Parent
class. Therefore only Parent
class is initialized, and age
remains 0
.
12.4.1. When Initialization Occurs
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.
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 (§7.6) and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.
In your case you accessed a static field declared by Parent
, so only Parent
is initialized.