Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 799
César Barbosa Avatar asked Apr 26 '26 14:04

César Barbosa


1 Answers

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.

like image 68
Rohit Jain Avatar answered Apr 29 '26 02:04

Rohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!