英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论