Java: Abstract GeometricShape Class with Triangle and Square Subclasses
Write a Java program to create an abstract class GeometricShape with abstract methods area() and perimeter(). Create subclasses Triangle and Square that extend the GeometricShape class and implement the respective methods to calculate the area and perimeter of each shape.
Sample Solution:
Java Code:
Output:
Triangle Area: 9.921567416492215 Triangle Perimeter: 15.0 Square Area: 36.0 Square Perimeter: 24.0
Explanation:
In the above exercise -
- The abstract class GeometricShape has two abstract methods: area() and perimeter(). The subclasses Triangle and Square extend the GeometricShape class and provide their own implementations for these abstract methods.
- The "Triangle" class calculates the area and perimeter of a triangle using its three sides, while the "Square" class calculates the area and perimeter of a square using its side length.
- In the main method, we create instances of Triangle and Square, and then call the area() and perimeter() methods on each object to calculate and display the respective area and perimeter.
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program where the "Triangle" subclass adds a method to determine if it is an isosceles triangle.
- Write a Java program where the "Square" subclass implements a method to check if it is a perfect square.
- Write a Java program where the "GeometricShape" class includes a method to check if one shape can fit inside another.
- Write a Java program where the "Triangle" subclass includes a method to classify triangles based on their angles.
Go to:
Java Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?