Java Polymorphism - Shape Class with Circle, Rectangle, and Triangle Subclasses for Area and Perimeter Calculation
Write a Java program to create a class Shape with methods getArea() and getPerimeter(). Create three subclasses: Circle, Rectangle, and Triangle. Override the getArea() and getPerimeter() methods in each subclass to calculate and return the area and perimeter of the respective shapes.
In the given exercise, here is a simple diagram illustrating polymorphism implementation:

In the above diagram, the Circle, Rectangle, and Triangle classes have the getArea() and getPerimeter() methods. These methods allow them to calculate and return the area and perimeter specific to each shape.
Sample Solution:
Java Code:
Output:
Radius of the Circle4.0 Area of the Circle: 50.26548245743669 Perimeter of the Circle: 25.132741228718345 Sides of the rectangle are: 4.0,6.0 Area of the Rectangle: 24.0 Perimeter of the Rectangle: 20.0 Sides of the Traiangel are: 3.0,4.0,5.0 Area of the Triangle: 6.0 Perimeter of the Triangle: 12.0
Flowchart:





For more Practice: Solve these Related Problems:
- Write a Java program where the "Shape" class includes a method to check if two shapes have equal area.
- Write a Java program where the "Shape" class implements a method to rotate the shape by a given angle.
- Write a Java program where the "Shape" class calculates the difference in perimeter between two shapes.
- Write a Java program where the "Shape" class supports color properties with predefined values.
Go to:
Java Code Editor:
Contribute your code and comments through Disqus.
PREV : Sports Class with Football, Basketball, and Rugby Subclasses for Playing Statements.
NEXT : Animal Base Class with Bird and Panthera Subclasses.
What is the difficulty level of this exercise?