简体   繁体   English

Java中的协方差和重载

[英]Covariance and Overloading in Java

class A {
   boolean f(A a) { return true; }
}
class B extends A {
   boolean f(A a) { return false; } // override A.f(A)
   boolean f(B b) { return true; }  // overload A.f
}

void f() {  
   A a = new A();
   A ab = new B();
   B b = new B();
   ab.f(a); ab.f(ab); ab.f(b); //(1) false, false, *false*
   b.f(a); b.f(ab); b.f(b);    //(2) false, false, true
}

Can you please explain the first line last false output, why it is not true? 你能解释一下最后一行的错误输出,为什么不是真的?

can you please explain the first line last false output, why it is not true? 你能解释一下最后一行的错误输出吗,为什么不是真的?

The compile-time type of ab is A , so the compiler - which is what performs overload resolution - determines that the only valid method signature is f(A a) , so it calls that. ab的编译时类型是A ,因此编译器 - 执行重载决策 - 确定唯一有效的方法签名是f(A a) ,因此它调用它。

At execution time, that method signature is executed as Bf(A a) because B overrides it. 执行时,该方法签名作为Bf(A a)执行,因为B覆盖它。

Always remember that the signature is chosen at compile time (overloading) but the implementation is chosen at execution time (overriding). 始终记住在编译时选择签名 (重载),但在执行时选择实现 (覆盖)。

Well..because you are calling on type of A. So you can call only version of f(A a). 嗯..因为你正在调用A的类型。所以你只能调用f(A a)的版本。 that's returning false in B. 在B.中返回false

Since you are using the object type of A, you can call only f(AA). 由于您使用的是A的对象类型,因此只能调用f(AA)。 Because B overrides it. 因为B会覆盖它。

can you please explain the first line last false output, why it is not true? 你能解释一下最后一行的错误输出吗,为什么不是真的?

Think otherwise :- 不这么想: -

try commenting below in class B (the overriding code) 尝试在B类下面评论(重写代码)

boolean f(A a) { return false; } // override A.f(A)

and add syso in Class A in this method --> boolean f(A a){....} 并在此方法的A类中添加syso - > boolean f(A a){....}

Then you'll see, ab.f(A a) or ab.f(B b) will invoke f(A a) method of class A only. 然后你会看到, ab.f(A a)ab.f(B b)只会调用f(A a)类的f(A a)方法。

As ab is of type A. 由于ab是A类型。

Also please note - You'll not be able to call any method of class B as well from object ab. 另请注意 - 您也无法从对象ab调用任何B类方法。

Hope this further adds more clarification to above brilliant answers. 希望这进一步增加了对上述精彩答案的更多澄清。

Lastly, you may seek this now --> Why do we assign a parent reference to the child object in Java? 最后,您现在可以寻求这个 - > 为什么我们在Java中为子对象分配父引用?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM