You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.3 KiB

abstract class Shape {
public abstract double getArea();
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
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;
}
public double getArea() {
return length * width;
}
}
class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
public double getArea() {
return 0.5 * base * height;
}
}
class ShapeUtil {
public static void printArea(Shape shape) {
System.out.println(shape.getArea());
}
}
// 关键修改:类名与文件名完全一致
public class 图形面积计算器重构 {
public static void main(String[] args) {
Shape circle = new Circle(2);
Shape rectangle = new Rectangle(3, 4);
Shape triangle = new Triangle(3, 4);
ShapeUtil.printArea(circle);
ShapeUtil.printArea(rectangle);
ShapeUtil.printArea(triangle);
}
}