Java Covariants

后端 未结 7 778
臣服心动
臣服心动 2021-01-01 22:26
public class CovariantTest {
    public A getObj() {
        return new A();
    }

    public static void main(String[] args) {
        CovariantTest c = new SubCov         


        
相关标签:
7条回答
  • 2021-01-01 23:17

    c is typed as CovariantTest at compile time and thus the call to c.getObj() is bound to the method CovariantTest.getObj() at compile time (and that can't be modified at runtime).

    Also, x exists in both A and B (it is shadowed, not overridden). Because the method being called is CovariantTest.getObj() and that method works with A, the x being retrieved is A.x even though the actual object is of type B.

    0 讨论(0)
提交回复
热议问题