Dynamic polymorphism is the ability of an object to invoke the appropriate method based on its runtime type, rather than its compile-time type. In Java, dynamic polymorphism is achieved by using the reference type of the superclass and the object type of the subclass. For example, suppose you have an array of Animal objects that contain different subclasses of Animal. You can loop through the array and call the makeSound method on each element, and the program will execute the overridden method of each subclass.
Animal[] animals = new Animal[3];
animals[0] = new Dog();
animals[1] = new Cat();
animals[2] = new Bird();
for (Animal animal : animals) {
animal.makeSound();
}
The output of this code will be:
Similarly, you can use an array of Shape objects that contain different subclasses of Shape. You can loop through the array and call the getArea and getColor methods on each element, and the program will execute the overridden and inherited methods of each subclass.
Shape[] shapes = new Shape[2];
shapes[0] = new Circle("red", 2.0);
shapes[1] = new Rectangle("blue", 3.0, 4.0);
for (Shape shape : shapes) {
System.out.println("The area of the " + shape.getColor() + " shape is " + shape.getArea());
}
The output of this code will be:
The area of the red shape is 12.566370614359172
The area of the blue shape is 12.0