Polymorphic Array of Shapes

This program demonstrates polymorphic arrays with abstract class Shape.

Problem Statement

Write a Java program to store multiple Shape objects (Circle, Rectangle) in an array and call their methods.

Source Code

1 abstract class Shape {
2 abstract void draw();
3 }
4 class Circle extends Shape {
5 void draw(){ System.out.println("Drawing Circle"); }
6 }
7 class Rectangle extends Shape {
8 void draw(){ System.out.println("Drawing Rectangle"); }
9 }
10 public class PolymorphicArrayShapes {
11 public static void main(String[] args) {
12 System.out.println("Eduinq Polymorphic Array of Shapes");
13 Shape[] arr={new Circle(),new Rectangle()};
14 for(Shape s:arr) s.draw();
15 }
16 }

Program Output

Eduinq Polymorphic Array of Shapes
Drawing Circle
Drawing Rectangle

Explanation

Abstract class Shape defines method draw(). - Subclasses implement their own version of draw(). - Array of Shape holds different subclass objects. - Polymorphism ensures correct method executes for each object at runtime, demonstrating flexible design. Conclusion: Shows how polymorphic arrays work with abstract classes.

Quick Links to Explore