Abstract Shapes
Completed
Create an abstract class Shape with abstract double area() and a concrete String describe(). Implement Circle, Rect and Triangle. Read shapes and print each description (area with 2 decimals), then the total area.
Input
n, then lines circle r, rect w h, triangle b h.
Output
n + 1 lines.
Example
Input
3 circle 1 rect 2 3 triangle 4 5
Output
circle area 3.14 rect area 6.00 triangle area 10.00 total 19.14
Editor
Java
Hints
An abstract method has no body; every concrete subclass must implement it.
You can't create an object of an abstract class.
Solution explanation
The shared describe() works for every shape because each one supplies its own area().
Show solution
import java.util.Scanner;
abstract class Shape {
abstract double area();
abstract String name();
String describe() {
return String.format("%s area %.2f", name(), area());
}
}
class Circle extends Shape {
final double r;
Circle(double r) { this.r = r; }
double area() { return Math.PI * r * r; }
String name() { return "circle"; }
}
class Rect extends Shape {
final double w, h;
Rect(double w, double h) { this.w = w; this.h = h; }
double area() { return w * h; }
String name() { return "rect"; }
}
class Triangle extends Shape {
final double b, h;
Triangle(double b, double h) { this.b = b; this.h = h; }
double area() { return b * h / 2; }
String name() { return "triangle"; }
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
double total = 0;
for (int i = 0; i < n; i++) {
String kind = sc.next();
Shape s;
if (kind.equals("circle")) {
s = new Circle(sc.nextDouble());
} else if (kind.equals("rect")) {
s = new Rect(sc.nextDouble(), sc.nextDouble());
} else {
s = new Triangle(sc.nextDouble(), sc.nextDouble());
}
System.out.println(s.describe());
total += s.area();
}
System.out.printf("total %.2f%n", total);
}
}