23,404
社区成员
发帖
与我相关
我的任务
分享
public class TestShape {
public static void main(String[] args) {
Shape shape1 = new Circle(10);
Shape shape2 = new Rectangle(5,10);
Shape shape3 = new Triangle(1,2,3); // a, b, c
Shape shape4 = new Trapezoid(3, 5, 4); // a, b, h
double area = countArea(shape1, shape2, shape3, shape4);
System.out.println(area);
}
private static double countArea(Shape...shapes) {
double area = 0.0;
for (Shape shape : shapes) area += shape.getArea();
return area;
}
}
abstract class Shape {
public abstract double getArea();
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double getArea() {
return length*width;
}
}
class Triangle extends Shape {
private double a;
private double b;
private double c;
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public double getArea() {
double p = (a + b + c) / 2;
return Math.sqrt(p * (p-a) * (p-b) * (p-c));
}
}
class Trapezoid extends Shape {
private double a;
private double b;
private double h;
public Trapezoid(double a, double b, double h) {
this.a = a;
this.b = b;
this.h = h;
}
@Override
public double getArea() {
return (a + b) * h / 2;
}
}