Java Runtime Polymorphism
In Java, runtime polymorphism is a mechanism by which a subclass can share the behavior of its superclass. It is also known as dynamic method dispatch.
Syntax
class SuperClass {
void method() {
System.out.println("Superclass method");
}
}
class SubClass extends SuperClass {
void method() {
System.out.println("Subclass method");
}
}
SuperClass obj = new SubClass();
obj.method();
Example
class Animal {
void sound() {
System.out.println("Animal is making a sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog is barking");
}
}
class Cat extends Animal {
void sound() {
System.out.println("Cat is meowing");
}
}
class Main {
public static void main(String[] args) {
Animal animal1 = new Animal();
Animal animal2 = new Dog();
Animal animal3 = new Cat();
animal1.sound();
animal2.sound();
animal3.sound();
}
}
Output
Animal is making a sound
Dog is barking
Cat is meowing
Explanation
In the example above, we have an Animal superclass and two subclasses Dog and Cat which extend the superclass. Each subclass has its own implementation of the sound() method.
In the Main class, we create three Animal objects animal1, animal2 and animal3. We initialize animal2 with a Dog object and animal3 with a Cat object.
When the sound() method is called on each Animal object, the implementation of the subclass is used. This is because of runtime polymorphism.
Use
Runtime polymorphism is used extensively in object-oriented programming to create code that is more modular, extensible and easier to maintain. It allows for code reuse and encourages inheritance.
Important Points
- Runtime polymorphism is a mechanism by which a subclass can share the behavior of its superclass.
- It is also known as dynamic method dispatch.
- The method invoked is determined at runtime, not at compile time, based on the type of the object.
- It is used to create modular, extensible and maintainable code.
- It allows for code reuse and encourages inheritance.
Summary
Runtime polymorphism is a powerful mechanism in Java that allows for code reuse and encourages inheritance. It is a key concept in object-oriented programming and is used extensively in creating modular, extensible and maintainable code.