Middle
What is dynamic polymorphism in Java?
sobes.tech AI
Answer from AI
Dynamic (or runtime polymorphism) is implemented through method overriding. This means that the decision about which method will be called is made at runtime, not at compile time.
Key points:
- Inheritance: Requires a class hierarchy where a subclass inherits from a superclass.
- Overriding: The subclass provides its own implementation of a method that is already declared in the superclass.
- Reference to superclass: An object of a subclass can be assigned to a reference of the superclass type.
- Method call: When calling an overridden method through a reference to the superclass, the implementation from the actual object (subclass) will be executed.
Example:
// Superclass
class Animal {
public void makeSound() {
System.out.println("Unknown sound");
}
}
// Subclass
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
// Subclass
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow!");
}
}
// Using polymorphism
class Main {
public static void main(String[] args) {
Animal myDog = new Dog(); // Reference to superclass points to subclass object
Animal myCat = new Cat();
myDog.makeSound(); // Calls method from Dog
myCat.makeSound(); // Calls method from Cat
}
}
Advantages:
- Flexibility: Allows handling objects of different subclasses uniformly through a common superclass reference.
- Extensibility: Easily add new subclasses without changing existing code that uses the superclass reference.
- Code simplification: Enables writing more generalized code.