java - 为什么在这个例子中没有调用子类方法,因为它在 Java 的动态多态中被调用?

标签 java inheritance

我做了一些研究,但我无法找到为什么在下面的示例中没有发生运行时多态性。 根据我的理解,应该在 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/

相关文章:

java - 如何使用 RestAssured 验证响应中的值列表

java - 错误 java The method combinationSum(int[], int, List<Integer>) in the type Solution is not applicable for the arguments (int[], int, boolean)

java - 实例化通用抽象类的子(具体)类,其构造函数需要其他参数类

c++ - 为什么要在 C++ 中为抽象类声明虚拟析构函数?

Java:当 B 扩展 A 时,A x = new A() 和 A x = new B() 之间的区别

java - csv 文件的内容显示在网页上,而不是正确的文件下载

java - 套接字 IO 事件多次触发 NodeJS

java - GWT - Netbeans 无法启动开发模式

java - 如何解决java聚合中的错误输出错误?

python - 在 Python 中继承 int