<分区>
我正在尝试为该声明找到证据 - 关键字 super
是对父类的引用,就像关键字 this
是对当前类的引用一样。
我在 Java A->B->C 中尝试多级继承:A 类是祖父类,B 类是父类,C 类是子类。
我在所有三个类中声明了一个变量 X
,其值分别为 (A:x=100,B:x=200,C:x=300)
在子类构造函数中,我正在打印值。但是,转换不适用于 super
关键字,而适用于 this
关键字。
((A)super).x
不工作,但是 ((A)this).x
工作。
class A {
int x = 100;
}
class B extends A {
int x = 200;
}
public class C extends B {
int x = 300;
public C () {
System.out.println(this.x); //OP = 300
System.out.println(super.x); // OP = 200
System.out.println(((A)this).x);// OP = 100
System.out.println(((A)super).x); // Giving Compile time Error.. Why?
B reftoB = new B();
System.out.println(((A)reftoB).x); // OP = 100
}
public static void main(String[] args) {
C t1= new C();
}
}
我希望 System.out.println(((A)super).x)
的输出是 100
,但它给出了编译时错误。
所以我的问题是,如果 super
是对父类的引用,那么为什么不对它进行类型转换?