Runtime Polymorphism in Java

Runtime polymorphism, also known as dynamic method dispatch, is a feature in Java that allows a method to be called based on the object being referenced at runtime. It enables a single function or method to behave differently depending on the object that it is acting upon, promoting flexibility and reusability in code.

Key Points on Runtime Polymorphism:

Example of Runtime Polymorphism in Java:

This example demonstrates runtime polymorphism using method overriding.

Code Example

class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    void sound() {
        System.out.println("Dog barks");
    }
}

class Cat extends Animal {
    void sound() {
        System.out.println("Cat meows");
    }
}

public class RuntimePolymorphismExample {
    public static void main(String[] args) {
        Animal myAnimal; // Declare an Animal reference
        myAnimal = new Dog(); // Animal reference points to Dog
        myAnimal.sound(); // Outputs: Dog barks

        myAnimal = new Cat(); // Animal reference now points to Cat
        myAnimal.sound(); // Outputs: Cat meows
    }
}

Output

Dog barks
Cat meows

Detailed Explanation:

Runtime polymorphism is a powerful feature in Java that enhances the flexibility and maintainability of code by allowing methods to behave differently based on the actual object type at runtime. By leveraging this feature, developers can create more dynamic and responsive applications that adapt to varying runtime conditions.