Runtime Polymorphism


Runtime Polymorphism

In this article, we are going to cover the Java Runtime Polymorphism. “Poly” stands for “many,” and “morph” means “type.” So, polymorphism means many types or different types. Java achieves its Runtime Polymorphism before running the code and after compilation of the code.

@Override notation is used in Java to point out which method we need to override.

Java Runtime Polymorphism overrides the methods when the method has identical names, arguments, return types, and type as of their parent class, but the methods have different functionalities.

A method having identical names, arguments, type as, and return type can override the functionalities of the previous method. This is how runtime polymorphism works in Java.

When we call a child class method from its parent class, the type of method indicates which method functionalities to be called or invoked by the JVM at the runtime after the code compilation. That is why it is called runtime polymorphism. It is referred to as be “Dynamic Method.” The reason behind calling runtime polymorphism a dynamic method is because it decides the method invocation at the run time as per the object by JVM,

Java Runtime Polymorphism is also known as “Late Binding” because binding of the method and objects will be decided later, i.e., after compilation.

When did the Runtime Polymorphism work?

  • When the name of the child and parent class is the same.
  • When the parameters of the child and the parent class is identical (in number of parameters and their respective return type)
  • When the child and the parent class has an IS-A relation (inheritance).

Limitation of Java Runtime Polymorphism:-

  • Private methods can not be overridden.
  • Final methods can not be overridden.
  • Static methods can not be overridden.

Conclusion:

Run the above example codes on your compilers y yourself and match the output.

Example:

Com.knowledge2life public class Main{ void run(){System.out.println("knowledge2life");} } class poly extends Main{ void run(){System.out.println("knowledge2life learning website");} public static void main(String args[]){ Main b = new poly();//upcasting b.run(); } }

OUTPUT:

knowledge2life learning website