What is dynamic polymorphism?
Dynamic Polymorphism
- 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 decides which method is to execute at runtime.
- It can be achieved through dynamic binding.
- It happens between different classes.
- It is required where a subclass object is assigned to a super-class object for dynamic polymorphism.
- Inheritance involved in dynamic polymorphism.
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).
Demo.java
//parent class
class Sample
{
//method of the parent class
public void display()
{
System.out.println("Overridden Method");
}
}
//derived or child class
public class Demo extends Sample
{
//method of child class
public void display()
{
System.out.printIn("Overriding Method");
}
public static void main(String args[])
{
//assigning a child class object to parent class reference
Sample obj = new Demo();
//invoking display() method
obj.display();
}
}
Output:Overriding Method
Comments
Post a Comment