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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!