为什么晚期绑定不按我预期的方式工作?

huangapple go评论96阅读模式
英文:

Why is Late Binding not working as i expected?

问题

以下是要翻译的部分:

我本来期望 obj.m(new E()) 引用的是在类H中定义的方法 m(E c),但出于某种我不理解的原因,实际上调用了类B中的方法。

英文:

The following code outputs 7:

  1. public class GuessTheAnswer {
  2. public static void main(String[] args) {
  3. A obj = new H();
  4. int jj;
  5. jj = obj.m(new E());
  6. System.out.println(jj);
  7. }
  8. }
  9. class A {
  10. public int m(C c) { return 8; }
  11. }
  12. class B extends A {
  13. public int m(C c) { return 7; }
  14. public int m(D c) { return 6; }
  15. public int m(E c) { return 5; }
  16. }
  17. class C {}
  18. class D extends C {}
  19. class E extends D {}
  20. interface I {
  21. public int m(I obj);
  22. }
  23. class H extends B implements I{
  24. public int m(I c) { return 12; }
  25. public int m(D c) { return 13; }
  26. public int m(E c) { return 14; }
  27. }

I would have expected obj.m(new E()) to refer to the method m(E c) defined in class H, but for some reason i don't understand the method in class B is called instead.

答案1

得分: 3

这是发生的情况:

obj 的声明类型是 A,因此只有在 A 内定义的方法会被考虑。而 A 唯一拥有的方法是 int m(C c)。只有这个方法及其重写版本会成为绑定的候选项。
H 中声明的方法是这个方法的重载版本,因此在主函数内进行方法调用时无法访问它们。

英文:

That's what happens:

obj is of declared type A, so only methods that are defined inside A are taken into account. And the only method that A has is int m(C c). Only this method and its overridden versions are going to be candidates for the binding.
The methods declared in H are overloaded versions of this method, so they are not accessible when you make a method call inside main.

huangapple
  • 本文由 发表于 2023年6月15日 16:22:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76480497.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定