简体   繁体   中英

Overloading and Polymorphism

I wish someone would explain me how this decision was taken. I understand that, the overloaded version is chosen based on the declared type, but why, on the second call, the decision was taken based the runtime type?

    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...");
        }
    }

Thanks in advance!

Your Parent class reference is referring to Child class object:

Parent polymorphicInstance = new Child();

So, when you pass the reference in call method, the actual method invoked is the one with Parent parameter type only. But when you call the method doSomething() , on parent reference:

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

It will call doSomething() method, that you have overridden in Child class.


This is the classic case of polymorphism . Suppose you have a class Shape and a subclass Circle , which overrides the method calculateArea() defined in Shape class.

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

When you override a super class method in subclass, then the actual method invoked is decided at runtime, based on what actual object your super class reference points to. This is called Dynamic Dispatch of method call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM