What is Run Time Polymorphism? Explain with an example.
Q.) What is Run Time Polymorphism? Explain with an example.
Subject: Object Oriented Programming and MethodologyRun Time Polymorphism:
- It is a critical concept in object-oriented programming (OOP) that allows objects of different classes to be treated as instances of a common superclass or interface.
- It enables objects to behave differently based on their actual type, even though they may all be referred to using the same variable type.
Mechanism of Runtime Polymorphism:
- This concept is achieved through the process of method overriding.
- In method overriding, a subclass redefines a method of the superclass with the same name and signature but different implementation.
- When a method is called on an object using a reference of the superclass, the compiler determines which method to execute based on the actual type of the object at runtime.
- This allows objects of different subclasses to respond differently to the same method call, even though they all belong to the same superclass or implement the same interface.
Example:
- Consider the following class hierarchy:
class Animal {
public void speak() {
System.out.println("Animal speaks");
}
}
class Dog extends Animal {
@Override
public void speak() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
@Override
public void speak() {
System.out.println("Cat meows");
}
}
- In this example, the
Animal
class defines aspeak()
method that prints "Animal speaks." The
Dog
andCat
classes extend theAnimal
class and override thespeak()
method to print "Dog barks" and "Cat meows," respectively.Now, consider the following code:
Animal animal = new Dog();
animal.speak(); // Output: Dog barks
Animal animal = new Cat();
animal.speak(); // Output: Cat meows
- In this code, we create an
Animal
reference variable and assign an object of either aDog
orCat
class to it. - When we call the
speak()
method on theanimal
reference, the actual method that gets executed depends on the type of the object referenced byanimal
. - If
animal
references aDog
object, theDog
class'sspeak()
method is called, resulting in the "Dog barks" output. - If
animal
references aCat
object, theCat
class'sspeak()
method is called, resulting in the "Cat meows" output.
This demonstrates how runtime polymorphism allows objects of different classes to be treated uniformly through a common interface or superclass, while still maintaining their individual behaviors.