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.

48 lines
1.3 KiB

package com.trae.shape;
/**
* 形状工具类
* 提供形状相关的工具方法
*/
public final class ShapeUtil {
/**
* 私有构造方法,防止实例化
*/
private ShapeUtil() {
// 工具类不允许实例化
}
/**
* 打印形状的面积
* @param shape 形状对象,可以是Circle、Rectangle或Triangle等任意Shape的子类
*/
public static void printArea(Shape shape) {
if (shape == null) {
System.out.println("形状对象不能为空");
return;
}
String shapeType = getShapeTypeName(shape);
double area = shape.getArea();
// 格式化输出,保留两位小数
System.out.printf("%s的面积是: %.2f\n", shapeType, area);
}
/**
* 获取形状类型的中文名称
* @param shape 形状对象
* @return 形状类型的中文名称
*/
private static String getShapeTypeName(Shape shape) {
if (shape instanceof Circle) {
return "圆形";
} else if (shape instanceof Rectangle) {
return "矩形";
} else if (shape instanceof Triangle) {
return "三角形";
} else {
return "未知形状";
}
}
}