Execution of Java static blocks in subclasses

不打扰是莪最后的温柔 提交于 2019-12-01 05:11: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.

In this case, Child.age is equivalent to Parent.age. JRE will treat it as Parent.age, that's why only Parent is statically initialized, and Child's static initializer is skipped.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!