diff --git a/w4/Circle.java b/w4/Circle.java new file mode 100644 index 0000000..f1a73d6 --- /dev/null +++ b/w4/Circle.java @@ -0,0 +1,23 @@ +/** + * 圆:面积 = π * r² + */ +public class Circle extends Shape { + + private final double radius; + + public Circle(double radius) { + if (radius <= 0) { + throw new IllegalArgumentException("半径必须为正数"); + } + this.radius = radius; + } + + public double getRadius() { + return radius; + } + + @Override + public double getArea() { + return Math.PI * radius * radius; + } +} diff --git a/w4/Rectangle.java b/w4/Rectangle.java new file mode 100644 index 0000000..7ca4f00 --- /dev/null +++ b/w4/Rectangle.java @@ -0,0 +1,29 @@ +/** + * 矩形:面积 = 宽 * 高 + */ +public class Rectangle extends Shape { + + private final double width; + private final double height; + + public Rectangle(double width, double height) { + if (width <= 0 || height <= 0) { + throw new IllegalArgumentException("宽和高必须为正数"); + } + this.width = width; + this.height = height; + } + + public double getWidth() { + return width; + } + + public double getHeight() { + return height; + } + + @Override + public double getArea() { + return width * height; + } +} diff --git a/w4/Shape.java b/w4/Shape.java new file mode 100644 index 0000000..dd41697 --- /dev/null +++ b/w4/Shape.java @@ -0,0 +1,10 @@ +/** + * 图形抽象基类:统一多态入口,具体面积由子类实现。 + */ +public abstract class Shape { + + /** + * @return 图形面积(具体单位由子类语义决定,如平方厘米) + */ + public abstract double getArea(); +} diff --git a/w4/ShapeCalculatorDemo.java b/w4/ShapeCalculatorDemo.java new file mode 100644 index 0000000..4995e77 --- /dev/null +++ b/w4/ShapeCalculatorDemo.java @@ -0,0 +1,27 @@ +/** + * 演示:多态 —— 同一 {@link ShapeUtil#printArea(Shape)} 处理圆、矩形、三角形。 + * 运行:javac *.java 后执行 java ShapeCalculatorDemo + */ +public class ShapeCalculatorDemo { + + public static void main(String[] args) { + Shape circle = new Circle(3.0); + Shape rectangle = new Rectangle(4.0, 5.0); + Shape triangle = new Triangle(6.0, 4.0); + + System.out.println("—— 圆 ——"); + ShapeUtil.printArea(circle); + + System.out.println("—— 矩形 ——"); + ShapeUtil.printArea(rectangle); + + System.out.println("—— 三角形 ——"); + ShapeUtil.printArea(triangle); + + System.out.println("—— 多态数组统一处理 ——"); + Shape[] shapes = {circle, rectangle, triangle}; + for (Shape s : shapes) { + ShapeUtil.printArea(s); + } + } +} diff --git a/w4/ShapeUtil.java b/w4/ShapeUtil.java new file mode 100644 index 0000000..03127cc --- /dev/null +++ b/w4/ShapeUtil.java @@ -0,0 +1,22 @@ +/** + * 图形工具类:通过多态统一打印任意 {@link Shape} 的面积。 + */ +public final class ShapeUtil { + + private ShapeUtil() { + // 工具类禁止实例化 + } + + /** + * 打印给定图形的面积(保留两位小数,便于实验输出阅读)。 + * + * @param shape 任意 {@link Shape} 子类实例,可为 null(将给出提示) + */ + public static void printArea(Shape shape) { + if (shape == null) { + System.out.println("图形引用为空,无法计算面积。"); + return; + } + System.out.printf("该图形的面积为:%.2f%n", shape.getArea()); + } +}