我不清楚扩展课程的程序。鉴于以下代码,为什么输出为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;
}
答案 0 :(得分:3)
首先,字段不会被覆盖,所以这一切都等同于
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;
}
f()
类对象的RtsC
实现来自RtsB
,因为这是覆盖f()
的最低级别的类,因此使用其实现,并返回b
,3
。该值乘以10
,然后从a
添加到RtsA
,因为zorg
只知道x
的类型为RtsA
所以使用该字段。那是3 * 10 + 2 = 32
。
(请注意,RtsA
是抽象的这一事实根本没有出现;这大多只在你有抽象方法担心的时候才有意义。)