What is Run Time Polymorphism? Explain with an example.


Q.) What is Run Time Polymorphism? Explain with an example.

Subject: Object Oriented Programming and Methodology

Run 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 a speak() method that prints "Animal speaks."
  • The Dog and Cat classes extend the Animal class and override the speak() 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 a Dog or Cat class to it.
  • When we call the speak() method on the animal reference, the actual method that gets executed depends on the type of the object referenced by animal.
  • If animal references a Dog object, the Dog class's speak() method is called, resulting in the "Dog barks" output.
  • If animal references a Cat object, the Cat class's speak() 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.