继承 FINAL 字段并将 subclass 对象转换为父对象 class 以使用它
Inheriting a FINAL field and casting subclass object into parent class to use it
class Test {
public static final String FOO = "foo";
public static void main(String[] args) {
Test b = new Test();
Sub s = new Sub();
System.out.print(Test.FOO); /* Prints foo */
System.out.print(Sub.FOO); /* Prints bar */
System.out.print(b.FOO); /* Prints foo */
System.out.print(s.FOO); /* Prints bar */
System.out.print(((Test)s).FOO); /* Prints foo but Why?*/
} }
class Sub extends Test {public static final String FOO="bar";}
我正在阅读有关继承的内容,我发现即使您将 SUB CLASS 对象转换为 PARENT class 并尝试使用该对象调用重写方法(请参阅 here), SUBCLASS 方法将被调用。
但是在我的问题中,为什么即使对象类型是 Class Sub.,也会打印 Parent Class 变量值?
如果您使用 <expression>.staticMember
.
,静态成员由用于引用它的表达式的类型解析
在这种情况下 ((Test)s)
是类型 Test
的表达式,这就是为什么 Test.FOO
在 ((Test)s).FOO
.
中被引用的原因
请注意,使用实例引用静态成员是不好的做法,因为这只会导致混淆。始终使用 <ClassName>.staticMember
可以避免这种混淆,即使用
Test.FOO
或
Sub.FOO
class Test {
public static final String FOO = "foo";
public static void main(String[] args) {
Test b = new Test();
Sub s = new Sub();
System.out.print(Test.FOO); /* Prints foo */
System.out.print(Sub.FOO); /* Prints bar */
System.out.print(b.FOO); /* Prints foo */
System.out.print(s.FOO); /* Prints bar */
System.out.print(((Test)s).FOO); /* Prints foo but Why?*/
} }
class Sub extends Test {public static final String FOO="bar";}
我正在阅读有关继承的内容,我发现即使您将 SUB CLASS 对象转换为 PARENT class 并尝试使用该对象调用重写方法(请参阅 here), SUBCLASS 方法将被调用。
但是在我的问题中,为什么即使对象类型是 Class Sub.,也会打印 Parent Class 变量值?
如果您使用 <expression>.staticMember
.
在这种情况下 ((Test)s)
是类型 Test
的表达式,这就是为什么 Test.FOO
在 ((Test)s).FOO
.
请注意,使用实例引用静态成员是不好的做法,因为这只会导致混淆。始终使用 <ClassName>.staticMember
可以避免这种混淆,即使用
Test.FOO
或
Sub.FOO