Dynamic Polymorphism in Java
In Java, polymorphism is a concept of object-oriented programming that allows us to perform a single action in different forms. In this section, we will discuss only the dynamic polymorphism in Java.
The word polymorphism is a combination of two words i.e. ploy and morphs. The word poly means many and morphs means different forms. In short, a mechanism by which we can perform a single action in different ways.
Let's understand the meaning of polymorphism with a real-world example.
A person in a shop is a customer, in an office, he is an employee, in the home he is husband/ father/son, in a party he is guest. So, the same person possesses different roles in different places. It is called polymorphism.
Types of Polymorphism
There are two types of polymorphism in Java:
Dynamic polymorphism is a process or mechanism in which a call to an overridden method is to resolve at runtime rather than compile-time. It is also known as runtime polymorphism or dynamic method dispatch. We can achieve dynamic polymorphism by using the method overriding.
In this process, an overridden method is called through a reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.
Properties of Dynamic Polymorphism
It provides a specific implementation to a method that is already present in the parent class. it is used to achieve run-time polymorphism. Remember that, it is not possible to override the static method. Hence, we cannot override the main() method also because it is a static method.
Rules for Method Overriding
We call an overridden method through a reference of the parent class. The type of object decides which method is to be executed and it is decided by the JVM at runtime.
Example of Dynamic Polymorphism
In the following example, we have created two classes named Sample and Demo. The Sample class is a parent class and the Demo class is a child or derived class. The child class is overriding the dispaly() method of the parent class.
We have assigned the child class object to the parent class reference. So, in order to determine which method would be called, the type of the object would be decided by the JVM at run-time. It is the type of object that determines which version of the method would be called (not the type of reference).
Example of Method Overriding
The child class method is invoked.
In the above example, we have used an annotation @Override. It indicates that the child class method is over-writing its base class method.