Polymorphic Array Example
This program demonstrates polymorphic arrays.
Problem Statement
Write a Java program where array of Shape holds different subclass objects.
Source Code
| 1 | abstract class Shape { abstract void draw(); } |
| 2 | class Circle extends Shape { void draw(){ System.out.println("Eduinq Drawing Circle"); } } |
| 3 | class Rectangle extends Shape { void draw(){ System.out.println("Eduinq Drawing Rectangle"); } } |
| 4 | public class PolymorphicArray { |
| 5 | public static void main(String[] args) { |
| 6 | System.out.println("Eduinq Polymorphic Array"); |
| 7 | Shape[] shapes={ new Circle(), new Rectangle() }; |
| 8 | for(Shape s:shapes) s.draw(); |
| 9 | } |
| 10 | } |
Program Output
Eduinq Polymorphic Array Eduinq Drawing Circle Eduinq Drawing Rectangle
Explanation
Polymorphic arrays allow storage of different subclass objects in a single array of superclass type. - Each element executes its own overridden method at runtime. - This design is widely used in frameworks where collections hold heterogeneous objects but operate uniformly. - It demonstrates runtime polymorphism applied to arrays, ensuring flexibility and extensibility. Conclusion: Shows polymorphic array example.