我不清楚扩展类的过程。给定以下一段代码,为什么输出是 32?
class Rts {
public static void main(String[] args) {
System.out.println(zorg(new RtsC()));
}
static int zorg(RtsA x) {
return x.f()*10 + x.a;
}
}
abstract class RtsA {
int a = 2;
int f() { return a; }
}
class RtsB extends RtsA {
int a = 3;
int f() { return a; }
}
class RtsC extends RtsB {
int a = 4;
}
最佳答案
首先,字段不会被覆盖,所以这一切等同于
public class Rts {
public static void main(String[] args) {
System.out.println(zorg(new RtsC()));
}
static int zorg(RtsA x) {
return x.f()*10 + x.a;
}
}
abstract class RtsA {
int a = 2;
int f() { return a; }
}
class RtsB extends RtsA {
int b = 3;
int f() { return b; }
}
class RtsC extends RtsB {
int c = 4;
}
RtsC
类型对象的 f()
实现来自 RtsB
,因为它是覆盖的最低级类f()
,所以使用它的实现,返回b
,也就是3
。它乘以 10
,然后从 RtsA
添加到 a
,因为 zorg
只知道 x
是 RtsA
类型,因此使用该字段。那是 3 * 10 + 2 = 32
。
(请注意,RtsA
是抽象的这一事实根本没有涉及;这主要只在您需要担心抽象方法时才重要。)
关于扩展抽象类的Java过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32771634/