Runtime polymorphism, also known as dynamic polymorphism, is a key feature of object-oriented programming that allows a method to behave differently based on the actual object type at runtime.
It enables you to invoke methods on objects without knowing their specific types at compile time, promoting flexibility and extensibility in your code.
Runtime polymorphism is achieved through method overriding, where a subclass provides a specific implementation for a method that is already defined in its superclass.
When a method is called on an object of a subclass, the Java Virtual Machine (JVM) determines the actual type of the object at runtime and invokes the appropriate method based on the object's type.
Here's an example to illustrate runtime polymorphism in Java:
class Animal { void makeSound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { @Override void makeSound() { System.out.println("Dog barks"); } void getSpeed() { System.out.println("30-40 kmph"); } } class Cat extends Animal { @Override void makeSound() { System.out.println("Cat meows"); } void getSpeed() { System.out.println("40-50 kmph"); } } public class Main { public static void main(String[] args) { // Creating object of subclass and assign to superclass reference Animal animal1 = new Dog(); // Creating object of subclass and assign to superclass reference Animal animal2 = new Cat(); animal1.makeSound(); // Output: "Dog barks" animal2.makeSound(); // Output: "Cat meows" // We cannot call getSpeed() method using animal1 reference as it is of type Animal // animal1.getSpeed(); // Compile-time error // We can cast the reference back to Dog to access subclass-specific methods if (animal1 instanceof Dog) { Dog dog = (Dog) animal1; // Casting to subclass dog.getSpeed(); // Output: 30-40 kmph } } }
We have an "Animal" class with a "makeSound" method.
We have "Dog" and "Cat" subclasses that override the "makeSound" method with their specific implementations.
In the main method, we create objects of type "Dog" and "Cat" but assign them to variables of type "Animal".
When we call the "makeSound" method on these objects, the actual method invoked is determined at runtime based on the type of the object (either Dog or Cat), demonstrating runtime polymorphism.
Runtime polymorphism allows for code flexibility, as it enables us to write code that works with objects of different types without needing to know the specific types at compile time.
This promotes loose coupling and facilitates code reuse and maintenance in object-oriented programming.