Java: Abstract GeometricShape Class with Triangle and Square Subclasses
Java Abstract Class: Exercise-12 with Solution
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:
//GeometricShape.java
abstract class GeometricShape {
public abstract double area();
public abstract double perimeter();
}
//Triangle.java
class Triangle extends GeometricShape {
private double side1;
private double side2;
private double side3;
public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
@Override
public double area() {
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
@Override
public double perimeter() {
return side1 + side2 + side3;
}
}
//Square.java
class Square extends GeometricShape {
private double side;
public Square(double side) {
this.side = side;
}
@Override
public double area() {
return side * side;
}
@Override
public double perimeter() {
return 4 * side;
}
}
//Main.java
public class Main {
public static void main(String[] args) {
GeometricShape triangle = new Triangle(4, 5, 6);
GeometricShape square = new Square(6);
System.out.println("Triangle Area: " + triangle.area());
System.out.println("Triangle Perimeter: " + triangle.perimeter());
System.out.println("Square Area: " + square.area());
System.out.println("Square Perimeter: " + square.perimeter());
}
}
Sample 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:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Abstract Bird Class with Eagle and Hawk Subclasses.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics