java - 重载和多态

标签 java overloading

我希望有人能向我解释这个决定是如何做出的。我明白,重载版本是根据声明的类型选择的,但为什么在第二次调用时,决定是基于运行时类型?

    public class Test {
        public static void main(String[] args) {
            Parent polymorphicInstance = new Child();

            TestPolymorphicCall tp = new TestPolymorphicCall();
            tp.doSomething(polymorphicInstance);
            // outputs: Parent: doing something... 

            call(polymorphicInstance);
            // outputs: Child: I'm doing something too 
        }
        public static void call(Parent parent){
            parent.doSomething();
        }
        public static void call(Child child){
            child.doSomething();
        }
    }

    public class Parent {
        public void doSomething() {
            System.out.println("Parent: doing something...");
        }
    }
    public class Child extends Parent{
        @Override
        public void doSomething() {
            System.out.println("Child: I'm doing something too"); 
        }
    }

    public class TestPolymorphicCall {
        public void doSomething(Parent p) {
            System.out.println("Parent: doing something...");
        }
        public void doSomething(Child c) {
            System.out.println("Child: doing something...");
        }
    }

提前致谢!

最佳答案

您的Parent 类引用指的是Child 类对象:

Parent polymorphicInstance = new Child();

因此,当您在调用方法中传递引用时,实际调用的方法只是具有Parent 参数类型的方法。但是,当您在 parent 引用上调用方法 doSomething() 时:

public static void call(Parent parent){
    parent.doSomething();
}

它将调用 doSomething() 方法,该方法已在 Child 类中覆盖。


这是多态的经典案例。假设你有一个类 Shape 和一个子类 Circle,它覆盖了 Shape 类中定义的方法 calculateArea() .

Shape circle = new Circle();
// This will invoke the method in SubClass.
System.out.println(circle.calculateArea());

当您在子类中重写父类(super class)方法时,实际调用的方法将在运行时根据您的父类(super class)引用指向的实际对象来决定。这称为方法调用的动态调度

关于java - 重载和多态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18022857/

相关文章:

java - 如何在 Play 2.3 中启用 play-querydsl 插件?

c++ - 为什么 char 既没有符号也没有符号,而 wchar_t 是?

c++ - 重载括号 C++ 是个好主意

Javascript function() 文字重载

c++ - 所有重载方法的别名?

c++ - 为什么 C++ lambda 重载的行为不如预期?

java - 在java中创建一个可以接收不同类型的类

java - JSpinner 具有显示格式、仅数字和手动编辑

java - 引用 JDBC 持久化、非 JPA 实体的 JPA 带注释的实体

java - 加速 jasperreports