Java ProPolymorphism: Shape base class with Circle, Square, and Triangle subclasses
Write a Java program to create a base class Shape with methods draw() and calculateArea(). Create three subclasses: Circle, Square, and Triangle. Override the draw() method in each subclass to draw the respective shape, and override the calculateArea() method to calculate and return the area of each shape.
Sample Solution:
Java Code:
Output:
Drawing a circle Area: 153.93804002589985 Drawing a square Area: 144.0 Drawing a triangle Area: 7.5
Explanation:
In the above exercise -
- "Shape" is the base abstract class, with Circle, Square, and Triangle as its subclasses. Each subclass overrides the draw() method to provide their specific shape drawing implementation. It also overrides the calculateArea() method to calculate and return the area of each shape.
- In the "Main()" class, we have a static method drawShapeAndCalculateArea(Shape shape) that takes an object of the base class Shape as a parameter. Inside this method, we call the draw() and calculateArea() methods on the shape object. Since the drawShapeAndCalculateArea method takes a Shape type parameter, it can accept objects of all three subclasses: Circle, Square, and Triangle, thanks to polymorphism.
Flowchart:





For more Practice: Solve these Related Problems:
- Write a Java program where the "Shape" class supports filling the shape with a specific pattern.
- Write a Java program where the "Shape" class calculates the aspect ratio of each shape.
- Write a Java program where the "Shape" class determines the shape with the largest area among a list of shapes.
- Write a Java program where the "Shape" class includes a method to check if two shapes are congruent.
Go to:
Java Code Editor:
Contribute your code and comments through Disqus.
PREV : Animal Base Class with Bird and Panthera Subclasses.
NEXT : BankAccount base class with Savings, Checking Account subclasses.
What is the difficulty level of this exercise?