class G {
int x = 5;
}
class H extends G {
int x = 6;
}
public class CovariantTest {
public G getObject() {
System.out.println("g");
return new G();
}
public static void main(String[] args) {
CovariantTest c1 = new SubCovariantTest();
System.out.println(c1.getObject().x);
System.out.println(new H().x);
}
}
class SubCovariantTest extends CovariantTest {
public H getObject() {
System.out.println("h");
return new H();
}
}
输出:
h
5
6
显然 main 方法中的两个 println 语句是不一样的。从类 SubCovariant 的 getObject 方法返回的新 H() 对象如何分配给 G 引用?