Why method overriding is called runtime polymorphism in Java?

(Last Updated On: September 24, 2018)

Answer to why method overriding is called runtime polymorphism in java includes very simple code example with explanation, so you can understand easily.

Do you think answer is difficult? In fact, it super simple. Read till end.

 

“In Run time polymorphism methods get resolved at Run Time”

Consider below example, there is a Car class with derived Cars Maruti and Hundai. Both classes have overridden run method of base class Car.

 

There is another class Driving as below. By looking at the method drive(Car c), can you tell which car object, Maruti or Hundai will run?

NO, WE CAN NOT!!!. Hence, JVM also cannot decide by looking at them at compile time. JVM can only decide at run time, which object Maruti or Hundai to run. That’s why method overriding is called run time polymorphism.

 

 

NOTE: Note that in method overloading you can tell at compile time itself which method will be called, for example, in below class you know that f() will be called with no arguments and f(int a) will be called if we pass 1 int argument without running the program. Hence, in case of method overloading JVM can resolve the method at compile time itself.

 

 

 

Code Example of RunTime Polymorphism in Java

In this example, drive(Car c) method will receive object of multiple types of car from main() program and resolve and execute run() method for which object to run at run time. means , at the time of program execution.

main() program will create object of Driving class and multiple types of Car objects and will supply objects of car to drive method.

NOTE:

Main program uses base class Car reference and assign object of Maruti or Hundai Car object. e.g. Car m = new Maruti(); // base reference and Maruti class object.

 

 

Output:
Maruti running…
Hundai running…

 

NOTE:

If there is an interface  and multiple derived concrete classes, who implements and override methods of interfaces, the run time effect can also be seen .

Read the loose coupling example in java where Manager class constructor receives multiple classes and call the work() method. Workers objects are resolved at run time and call respective work() methods.