我做了一些研究,但我无法找到为什么在下面的示例中没有发生运行时多态性。 根据我的理解,应该在 child 中调用 foo(int a)。但输出的是“Parent with long”。有人可以解释一下吗?
class Parent {
public void foo() throws RuntimeException {
System.out.println("Parent with no Parameter");
}
public void foo(long a) {
System.out.println("Parent with long");
}
}
class Child extends Parent {
public void foo() {
System.out.println("Child with no parameter");
}
public void foo(int a) throws RuntimeException {
System.out.println("Child with int");
}
}
class Demo {
public static void main(String... args) {
Parent p = new Child();
int a = 10;
p.foo(a);
}
}
输出:
parent 长
最佳答案
多态性仅在方法具有完全相同的签名(相同数量和类型的参数)时适用。
关于java - 为什么在这个例子中没有调用子类方法,因为它在 Java 的动态多态中被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42455199/