首先,字段不会被覆盖,因此所有这些都相当于
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公司
是抽象的,根本没有涉及到这一点;只有当你需要担心抽象方法时,这才是最重要的。)