在子类中执行Java静态块 [英] Execution of Java static blocks in subclasses
问题描述
我正准备自己进行Java认证测试,我发现了一个与Java静态块执行相关的有趣问题。我花了很多时间阅读这个主题,但我找不到我想要的答案。
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.
我知道静态块在课时执行加载到JVM或调用main方法时,但是......
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);
}
}
输出为:
Child age is : 0
如果我在 -verbose:class
中包含详细输出,则输出为:
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]
我们在这里可以看到已加载子类进入JVM。
We can see here that Child class is loaded into JVM.
有人可以解释为什么 Child
类中的静态块未被执行?
Can someone explain why the static block from Child
class is not executed?
推荐答案
您看到 Child
类已加载,但它没有初始化。
You saw that Child
class was loaded, but it wasn't initialized.
访问 Child.age
不会导致 Child
class,因为 age
是 Parent
类的成员。因此,只初始化 Parent
类, age
仍为 0
。
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
.
类或接口类型T将在
第一次出现以下任何一个之前立即初始化:
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
-
T是一个类,并且创建了一个T实例。
T is a class and an instance of T is created.
调用由T声明的静态方法。
A static method declared by T is invoked.
分配由T声明的静态字段。
A static field declared by T is assigned.
使用T声明的静态字段,字段不是常量变量(§4.12.4)。
T是顶级类(§7.6),并且执行词汇嵌套在T(§8.1.3)中的断言语句(§14.10)。
T is a top level class (§7.6) and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.
在您的情况下,您访问了由 Parent
声明的静态字段,因此只有父
已初始化。
In your case you accessed a static field declared by Parent
, so only Parent
is initialized.
这篇关于在子类中执行Java静态块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!