LearnFrenzy
Sign in Take a free test

Abstraction · Abstraction Programs · Question 1

Abstract Shape with circle, square and triangle in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Write an abstract Shape with abstract area() and perimeter() and a concrete describe(); implement Circle, Square and EquilateralTriangle and print each description.

Solution
Main.java
abstract class Shape {
    abstract double area();
    abstract double perimeter();
    String describe() { return String.format("%-20s area %7.2f  perimeter %6.2f", getClass().getSimpleName(), area(), perimeter()); }
}

class Circle extends Shape {
    private final double r;
    Circle(double r) { this.r = r; }
    double area() { return Math.PI * r * r; }
    double perimeter() { return 2 * Math.PI * r; }
}

class Square extends Shape {
    private final double s;
    Square(double s) { this.s = s; }
    double area() { return s * s; }
    double perimeter() { return 4 * s; }
}

class EquilateralTriangle extends Shape {
    private final double s;
    EquilateralTriangle(double s) { this.s = s; }
    double area() { return Math.sqrt(3) / 4 * s * s; }
    double perimeter() { return 3 * s; }
}

public class Main {
    public static void main(String[] args) {
        Shape[] shapes = {new Circle(5), new Square(6), new EquilateralTriangle(8)};
        for (Shape s : shapes) System.out.println(s.describe());
    }
}

Output Verified by compiling and running

Circle               area   78.54  perimeter  31.42
Square               area   36.00  perimeter  24.00
EquilateralTriangle  area   27.71  perimeter  24.00

describe() is written once in the abstract class and works for every shape.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links