public class CovariantTest {
public A getObj() {
return new A();
}
public static void main(String[] args) {
CovariantTest c = new SubCovariantTest();
System.out.println(c.getObj().x);
}
}
class SubCovariantTest extends CovariantTest {
public B getObj() {
return new B();
}
}
class A {
int x = 5;
}
class B extends A {
int x = 6;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码在编译和运行时打印5.它使用过度返回方法的协变返回.
为什么它会打印5而不是6,因为它在SubCovariantTest类中执行overRidden方法getObj.
有人可以对此有所了解.谢谢.
java ×1