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

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

Why is Late Binding not working as i expected?

问题

以下是要翻译的部分:

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

英文:

The following code outputs 7:

public class GuessTheAnswer {
    public static void main(String[] args) {
        A obj = new H();
        int jj;
        jj = obj.m(new E());
        System.out.println(jj);
    }
}
class A {
    public int m(C c) { return 8; }
}
class B extends A {
    public int m(C c) { return 7; }
    public int m(D c) { return 6; }
    public int m(E c) { return 5; }
}

class C {}
class D extends C {}
class E extends D {}
interface I {
    public int m(I obj);
}
class H extends B implements I{
    public int m(I c) { return 12; }
    public int m(D c) { return 13; }
    public int m(E c) { return 14; }
}

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:

确定