java - 调用父类和子类中可用的方法时,在多态中选择了哪种方法?
问题描述
我不明白为什么该ab.m3()
方法调用父类的函数而不是子类的函数。我想也许将 new 传递Integer
给方法可能会调用父类的方法,因为Integer
is anObject
所以我尝试使用 anint
但它仍然给了我相同的结果!
public class A {
public void m1(){
System.out.println("A.m1");
}
public void m2(){
System.out.println("A.m2");
}
public void m3(Object x){
System.out.println("A.m3");
}
}
public class B extends A{
public void m1(){
System.out.println("B.m1");
}
public void m2(int x){
System.out.println("B.m2");
}
public void m3(int x){
System.out.println("B.m3");
}
public static void main(String[] argv){
A aa = new A();
A ab = new B();
int num = 2;
ab.m1();
ab.m2();
ab.m3(new Integer(2));
ab.m3(num);
}
}
输出:
B.m1
A.m2
A.m3
A.m3
解决方案
B.m3
不会覆盖A.m3
,因为参数列表不兼容。
A
因为is中唯一匹配的方法A.m3
,并且因为 中没有覆盖B
,所以A.m3
它将被调用。
推荐阅读
- javascript - React Native:在方法的渲染函数中使用变量
- linux - Bash:选择文件名中带有“ Tb ”的所有文件名
- java - 迭代矩阵和标记节点为已访问的岛数
- uwp - uno 平台:在 UserControl 中,如何使绘制动作无效
- r - 在 dplyr 中组合表格
- python-3.x - 冷启动推荐系统实现
- c - 程序在我打印出值时有效,但在我不打印时无效
- drop-down-menu - 自动完成下拉多选 swiftui
- html - CSS - 如何使带有图标和文本响应的水平手风琴
- google-apis-explorer - Google People API listDirectoryPeople 未返回目录中任何用户的姓名