【发布时间】:2019-06-23 05:33:26
【问题描述】:
我正在尝试为该声明找到证据 - 关键字 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 是对父类的引用,那么为什么类型转换不工作呢?
【问题讨论】:
-
这只是无效的语法。
super不能这样使用。它只能在直接字段访问/方法调用表达式中使用,而不会进行强制转换。 -
super指的是与this相同的实例。您尝试做的事情没有意义。 -
super不是“对父类的引用”。它是一个关键字,允许您引用继承的字段或方法。仅此而已。
标签: java