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.

80 lines
1.7 KiB

// Main.java
public class Main {
public static void main(String[] args) {
ShapeUtil util = new ShapeUtil();
// 测试圆形
Shape circle = new Circle(5);
System.out.print("圆形(半径5):");
util.printArea(circle);
// 测试矩形
Shape rectangle = new Rectangle(4, 6);
System.out.print("矩形(长4,宽6):");
util.printArea(rectangle);
// 测试三角形
Shape triangle = new Triangle(3, 4);
System.out.print("三角形(底3,高4):");
util.printArea(triangle);
}
}
// 抽象类 Shape(不加 public)
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 base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double getArea() {
return (base * height) / 2;
}
}
// 工具类
class ShapeUtil {
public void printArea(Shape shape) {
double area = shape.getArea();
System.out.printf("该图形的面积为:%.2f%n", area);
}
}