
Java Runtime Polymorphism
Runtime polymorphism, also known as dynamic polymorphism or method overriding, is one of the fundamental concepts of object-oriented programming in Java. It allows different classes to provide their own implementation of a method with the same name and signature, and the appropriate method is called at runtime based on the actual object type, enabling a more flexible and extensible design.
Here’s how runtime polymorphism works in Java:
- Method Overriding:
- To achieve runtime polymorphism, you need to override a method in a subclass with the same method signature as the superclass. The overridden method in the subclass provides a specific implementation.
- Polymorphic Behavior:
- When a method is called on an object, Java determines which method to invoke based on the actual class type of the object. This means that you can have multiple subclasses with their own implementations of the same method, and the appropriate method is invoked based on the object’s runtime type.
- Upcasting:
- You can achieve runtime polymorphism through upcasting, which involves treating a subclass object as an instance of its superclass. This is done by assigning an object of a subclass to a reference variable of the superclass type.
- Method Invocation:
- When a method is called on an object, Java checks the runtime type of the object and looks for the most specific implementation of the method in the class hierarchy.
Here’s an example illustrating runtime polymorphism:
class Animal {
void makeSound() {
System.out.println("Some generic animal sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Woof! Woof!");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow!");
}
}
public class Main {
public static void main(String[] args) {
Animal myPet = new Dog(); // Upcasting
myPet.makeSound(); // Calls the makeSound method of the Dog class
myPet = new Cat(); // Upcasting to a different subclass
myPet.makeSound(); // Calls the makeSound method of the Cat class
}
}
In this example, Animal
is the superclass with a makeSound
method, and Dog
and Cat
are subclasses that override the method. When you create objects and upcast them to the Animal
type, you can call the makeSound
method, and the appropriate overridden method is executed based on the actual runtime type of the object.
Runtime polymorphism is a powerful feature of object-oriented programming, as it allows for flexible, maintainable code by enabling you to add new subclasses or override methods without changing the existing code that uses those classes.