Java cast to superclass and call overload method(Java 转换为超类并调用重载方法)
问题描述
abstract class A {
int met(A a) {
return 0;
}
int met(B b) {
return 1;
}
int met(C c) {
return 2;
}
}
class B extends A {
int met(A a) {
return 3;
}
int met(B b) {
return 4;
}
int met(C c) {
return 5;
}
}
class C extends B {
int f() {
return ((A)this).met((A)this);
}
}
public class teste {
public static void main(String args[]) {
C x = new C();
System.out.println(x.f());
}
}
程序将返回 3,而我期待的是 0.为什么方法 f 中的第一个强制转换什么都不做而第二个有效?是不是因为A类和B类中的met方法被重载了,所以使用了静态绑定?
The program will return 3 and I was expecting 0. Why does the first cast in the method f do nothing and the second one works? Is it because in the A and B classes the met methods are overloaded and therefore static binding is used?
推荐答案
这就是多态的工作方式.看看这个例子:
That's just the way polymorphism works. Just consider this example:
A a = new C();
a.met(a);
这将按预期调用正确的方法B#met(...)
.对象的方法表不只是因为您更改了存储 Object
的变量的类型而改变,因为 Object
和它的方法之间的绑定是强于存储类型和相关方法之间的一种.第二种类型有效,因为输入的类型被强制转换为 A
,因此该方法将其识别为 A
(输入存储的类型比Object
类型).
This would as expected call the correct method B#met(...)
. The method-tables for an object don't just change because you change the type of the variable you stored the Object
in, since the binding between an Object
and it's methods is stronger than the one between the storage-type and the methods related to it. The second type works, because the type of the input is casted to A
and thus the method recognizes it as A
(the type of the input-storage has stronger binding than the Object
type).
这篇关于Java 转换为超类并调用重载方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 转换为超类并调用重载方法


- Eclipse 的最佳 XML 编辑器 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 获取数字的最后一位 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 转换 ldap 日期 2022-01-01