Execution of Java static blocks in subclasses

前端 未结 2 1003
感情败类
感情败类 2021-01-12 17:18

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

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-12 17:59

    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.

提交回复
热议问题