runtime polymorphism in java

Runtime polymorphism in Java is achieved through method overriding. Method overriding is a technique in which a subclass provides its own implementation of a method that is already defined in its superclass.

Here’s how runtime polymorphism works in Java:

  1. First, a superclass is created with a method that is marked as public and virtual (i.e., can be overridden).
public class Animal {
    public void makeSound() {
        System.out.println("The animal makes a sound");
    }
}
  1. Next, a subclass is created that inherits from the superclass and overrides the method with its own implementation.
public class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Meow");
    }
}
  1. A third class is created to test the runtime polymorphism.
public class TestPolymorphism {
    public static void main(String[] args) {
        Animal animal = new Animal(); // create an instance of the Animal class
        animal.makeSound(); // output: The animal makes a sound

        Animal cat = new Cat(); // create an instance of the Cat class using the Animal reference
        cat.makeSound(); // output: Meow
    }
}

In the example above, we create an instance of the Animal class and call its makeSound() method, which outputs “The animal makes a sound”. We then create an instance of the Cat class using the Animal reference, and call its makeSound() method, which outputs “Meow”.

The makeSound() method is overridden in the Cat class and the cat object is of type Animal, but it refers to an instance of Cat, so when we call makeSound() on the cat object, the overridden method in the Cat class is invoked, resulting in the output “Meow”.

This is an example of runtime polymorphism in Java, where the method invoked is determined at runtime based on the actual object being referred to by the reference variable, rather than at compile-time based on the type of the reference variable.

Share