Method overloading is one of the ways in which java supports dynamic method dispatch. Java dynamic method dispatch is also referred to as Runtime Polymorphism.
What is Runtime Polymorphism?
Runtime polymorphism is a mechanism in which a call to a method which is overridden is resolved at runtime rather than at compile time.
How Java Dynamic Method Dispatch implements Runtime Polymorphism ?
What happens in the program is as follows:
When an overridden method is called through a super class reference, Java determines which version of that method is to be executed based o the type of object being referred to at the time the call occurs. This determination is made at run time.
Let’s take an Example.
In these examples, in each program we have two classes: pClass and sub. pClass is the parent class and sub is the subclass. The subclass is overriding the method show() of the parent class.
Program 1:
// Parent Class class pClass { void show() { System.out.println("Overridden Method"); } } // sub class class sub extends pClass { void show() { System.out.println("Overriding Method"); } } class example { public static void main(String args[]) { sub s = new sub(); s.show(); } }
Output
Program 2
// Parent Class class pClass { void show() { System.out.println("Overridden Method"); } } // sub class class sub extends pClass { void show() { System.out.println("Overriding Method"); } } class example { public static void main(String args[]) { pClass s = new pClass(); s.show(); } }
Output
In program 1, we have created an object of the subclass or child class hence, at run time, the overriding function is called. Whereas, in program 2, we have created an object of the parent or base class hence, at runtime, the overridden function is called. So, we conclude that it is the type of object created which determines which version of the method is to be called. This determination is made at run time by the JVM.
What is upcasting?
When parent class reference variable refers to a child class object, it is known as upcasting.
Parent class objects can only to refer child class. Child class objects cannot refer to parent class.
If upcasting is used in a program then also dynamic method dispatch would take place and the function to be called will be determined at run time.
Example:
Let us take the same example as above with the difference in object creation and let’s have a look at the output here.
// Parent Class class pClass { void show() { System.out.println("Overridden Method"); } } // sub class class sub extends pClass { void show() { System.out.println("Overriding Method"); } } class example { public static void main(String args[]) { pClass s = new sub(); s.show(); } }