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.

67 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;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
// 矩形类
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
}
// 三角形类
class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double getArea() {
return 0.5 * base * height;
}
}
// 工具类
class ShapeUtil {
public void printArea(Shape shape) {
System.out.printf("面积:%.2f%n", shape.getArea());
}
}
// 主类(程序入口)
public class Main {
public static void main(String[] args) {
ShapeUtil util = new ShapeUtil();
util.printArea(new Circle(5));
util.printArea(new Rectangle(4, 6));
util.printArea(new Triangle(3, 4));
}
}