abstract class Shape { public abstract double getArea(); } class Circle extends Shape { private double radius; public Circle(double radius) { if (radius <= 0) { throw new IllegalArgumentException("半径必须为正数"); } 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) { if (width <= 0 || height <= 0) { throw new IllegalArgumentException("宽和高必须为正数"); } this.width = width; this.height = height; } @Override public double getArea() { return width * height; } } class Triangle extends Shape { private double a; private double b; private double c; public Triangle(double a, double b, double c) { if (a <= 0 || b <= 0 || c <= 0) { throw new IllegalArgumentException("边长必须为正数"); } if (a + b <= c || a + c <= b || b + c <= a) { throw new IllegalArgumentException("三边不满足三角形构成条件"); } this.a = a; this.b = b; this.c = c; } @Override public double getArea() { double s = (a + b + c) / 2; return Math.sqrt(s * (s - a) * (s - b) * (s - c)); } } class ShapeUtil { public static void printArea(Shape shape) { if (shape == null) { System.out.println("图形对象不能为空"); return; } System.out.printf("图形面积:%.2f%n", shape.getArea()); } } public class ShapeAreaCalculator { public static void main(String[] args) { try { Shape circle = new Circle(3); System.out.print("圆形:"); ShapeUtil.printArea(circle); Shape rectangle = new Rectangle(4, 5); System.out.print("矩形:"); ShapeUtil.printArea(rectangle); Shape triangle = new Triangle(3, 4, 5); System.out.print("三角形:"); ShapeUtil.printArea(triangle); } catch (IllegalArgumentException e) { System.out.println("错误:" + e.getMessage()); } } }