具有继承的静态块的行为 [英] Behavior of static blocks with inheritance
问题描述
我正在尝试使用这样的静态块:
I am trying to use static blocks like this:
我有一个名为的基类Base.java
public class Base {
static public int myVar;
}
派生类派生。 java
:
public class Derived extends Base {
static
{
Base.myVar = 10;
}
}
我的主
函数是这样的:
public static void main(String[] args) {
System.out.println(Derived.myVar);
System.out.println(Base.myVar);
}
这会将输出打印为 0 0
我预期的位置 10 0
。有人可以解释这种行为吗?另外,如果我希望我的派生类设置静态变量的值,我该如何实现呢?
This prints the out put as 0 0
where as I expected 10 0
. Can somebody explain this behavior? Also, if I want my derived classes to set the values for a static variable how can I achieve that?
推荐答案
据我所知。您不会调用任何派生
属性( myVar
属于 Base
,而不是派生
)。并且java没有从 Derived
运行静态块。如果你向 Derived
添加一些静态字段并访问它,那么java会执行所有静态块。
As I understand. You don't call any Derived
properties (myVar
belongs to Base
, not to Derived
). And java is not running static block from Derived
. If you add some static field to Derived
and access it, then java executes all static blocks.
class Base {
static public int myVar;
}
class Derived extends Base {
static public int myVar2;
static
{
Base.myVar = 10;
}
}
public class Main {
public static void main( String[] args ) throws Exception {
System.out.println(Derived.myVar2);
System.out.println(Base.myVar);
}
}
从java规范中,初始化类时(和静态)块被执行):
From java specification, when class is initialized (and static block got executed):
12.4.1初始化发生时类或接口类型T将在第一次出现之前立即初始化以下内容:
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是一个类,并且创建了一个T实例。
•T是一个类和一个声明的静态方法调用T。
•指定由T声明的静态字段。
•使用由T声明的静态字段,该字段不是常量变量(§4.12.4 )。$
•T是顶级类(第7.6节),并且执行在词典内嵌套在T(第8.1.3节)内的断言语句(第14.10节)。
• T is a class and an instance of T is created.
• T is a class and 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.
这篇关于具有继承的静态块的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!