编程语言
首页 > 编程语言> > java-重载和多态

java-重载和多态

作者:互联网

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

    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 polymorphicInstance = new Child();

因此,当您在调用方法中传递引用时,实际调用的方法仅是具有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());

当您在子类中重写超类方法时,所调用的实际方法将在运行时根据您的超类引用所指向的实际对象来确定.这称为方法调用的动态调度.

标签:overloading,java
来源: https://codeday.me/bug/20191030/1969010.html