使用子类名访问父类静态字段不会加载子类? [英] Accessing parent class static field using child class name doesn't load the child class?
问题描述
class A {
static int super_var = 1;
static {
System.out.println("super");
}
}
class B extends A {
static int sub_var = 2;
static {
System.out.println("sub");
}
}
public class Demo{
public static void main(String []args){
System.out.println(B.super_var);
}
}
输出为:
super
1
这意味着孩子班级不会加载或任何其他东西?它是如何工作的?
this means that the child class not going to load or any other thing? how is it works?
推荐答案
当您访问 static
字段时子类引用上的超类,只有声明该字段的类才会被加载和初始化,在这种情况下它是 A
。这在 JLS§ 12.4.1 - 初始化发生时:
When you access the static
fields of a super class on subclass reference, only the class that declares the field will be loaded and initialized, in this case it is A
. This is specified in JLS §12.4.1 - When Initialization Occurs:
对
static $ c $的引用c> field(§8.3.1.1)导致只初始化
实际声明它的类或接口,即使可能通过子类名称引用
,子接口或实现接口的
类。
A reference to a
static
field (§8.3.1.1) causes initialization of only the class or interface that actually declares it, even though it might be referred to through the name of a subclass, a subinterface, or a class that implements an interface.
强调我的。
所以在你的代码中,类 B
甚至不会被初始化,因此它的 static
块不会被执行。
So in your code, class B
would not even be initialized, and hence its static
block would not be executed.
这篇关于使用子类名访问父类静态字段不会加载子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!