java - 以 Parent 和 Child 类作为参数的方法重载

标签 java inheritance polymorphism overloading

<分区>

我有 3 个类 GrandParentParentChild,其中 Child extends ParentParent extends GrandParent

public class Main {
    void test(GrandParent gp){System.out.println("GrandParent");}
    void test(Parent p){System.out.println("Parent");}

    public static void main(String args[]){
        GrandParent obj = new Child();
        Main mainObj = new Main();
        mainObj.test(obj);  // This calls test(GrandParent gp)

        mainObj.test(new Child()); // This calss test(Parent gp)
    }
}

在上面的代码中,对 test() 方法的 2 次调用都使用 Child 对象调用了不同的方法。其中一个是编译时绑定(bind),另一个是运行时绑定(bind)。这对我来说听起来有点奇怪。你会如何解释这一点?

最佳答案

方法重载是编译时多态性。

方法覆盖是运行时多态性。

在您的例子中,您正在重载 Main 类的两个实例方法。

但是,由于我假设在您的上下文中 Child extends Parentnew Child() instanceof Parent == true 因此是 Child 是参数类型为 Parent 的方法 test 的有效参数。

在第一种情况下,您在方法 test 中传递了一个引用类型 GrandParent,并找到了准确的类型。

在第二种情况下,您在方法 test 中传递了一个引用类型 Child。最接近的匹配是 Parent,因此调用 test(Parent p)

关于java - 以 Parent 和 Child 类作为参数的方法重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24188517/

相关文章:

c++ - 派生到基隐式指针类型转换

c++ - 基指针中的派生对象如何调用基函数?

c++ - 在 Base* 数据结构中格式化和使用派生类的正确方法是什么?

c++ - 对 C++ 多态、可查找、二进制 I/O 接口(interface)的建议

java - java - 如何将具有空终止字符的字节数组转换为Java中的字符串?

java - 无法使用 Selenium 单击 href 链接

java - 为什么有些语言需要装箱和拆箱?

java - 如何在 .classpath 中添加对 .properties 文件的引用

php - Laravel 5.2 中 Controller 类的单继承

c++ - 有没有办法拥有更严格的泛型仿函数参数?