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 转换为超类并调用重载方法


基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01