问题描述
我有一个班级,超级
:
public class Super {
public static String foo = "foo";
}
我还有另一个班级, Sub
扩展超级
:
I also have another class, Sub
that extends Super
:
public class Sub extends Super {
static {
foo = "bar";
}
public static void main (String[] args) {
System.out.println(Super.foo);
}
}
当我运行它时,它打印出 bar
。
我的第三个(也是最后一个)课程是测试
:
When I run it, it prints out bar
.
My third (and last) class is Testing
:
public class Testing {
public static void main (String[] args) {
System.out.println(Super.foo);
System.out.println(Sub.foo);
System.out.println(Super.foo);
}
}
打印:
foo
foo
foo
我不明白为什么 foo
的内容会因您访问它的类别而异。任何人都可以解释一下吗?
I don't understand why the contents of foo
vary depending on what class you're accessing it from. Can anyone explain?
推荐答案
基本上这是类型初始化的问题。当 Sub foo
的值设置为bar
>已初始化。但是,在 Testing
类中,对 Sub.foo
的引用实际上被编译为对<$ c $的引用c> Super.foo ,所以它不会最终初始化 Sub
,所以 foo
永远不会变成bar
。
Basically it's a matter of type initialization. The value of foo
is set to "bar"
when Sub
is initialized. However, in your Testing
class, the reference to Sub.foo
is actually compiled into a reference to Super.foo
, so it doesn't end up initializing Sub
, so foo
never becomes "bar"
.
如果您将测试代码更改为:
If you change your Testing code to:
public class Testing {
public static void main (String[] args) {
Sub.main(args);
System.out.println(Super.foo);
System.out.println(Sub.foo);
System.out.println(Super.foo);
}
}
然后它会打印出bar四次,因为第一个语句会强制初始化 Sub
,这会改变 foo
的值。这根本不在于它的访问位置。
Then it would print out "bar" four times, because the first statement would force Sub
to be initialized, which would change the value of foo
. It's not a matter of where it's accessed from at all.
这篇关于规定Java中静态变量的继承有哪些规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!