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 检查调试符号状态? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01