From cfa49fbf9dd2b7ffb1c69b7962c581cc606d9b5f Mon Sep 17 00:00:00 2001 From: Chengwuyi <3394813085@qq.com> Date: Mon, 30 Mar 2026 12:59:52 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E6=96=87=E4=BB=B6=E8=87=B3?= =?UTF-8?q?=20'w5'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- w5/Main.java | 11 +++++++++++ w5/Rectangle.java | 14 ++++++++++++++ w5/Shape.java | 4 ++++ w5/ShapeUtil.java | 6 ++++++ w5/Triangle.java | 14 ++++++++++++++ 5 files changed, 49 insertions(+) create mode 100644 w5/Main.java create mode 100644 w5/Rectangle.java create mode 100644 w5/Shape.java create mode 100644 w5/ShapeUtil.java create mode 100644 w5/Triangle.java diff --git a/w5/Main.java b/w5/Main.java new file mode 100644 index 0000000..32c11d0 --- /dev/null +++ b/w5/Main.java @@ -0,0 +1,11 @@ +public class Main { + public static void main(String[] args) { + Shape circle = new Circle(5); + Shape rect = new Rectangle(4, 6); + Shape tri = new Triangle(3, 8); + + ShapeUtil.printArea(circle); // 面积为:78.54 + ShapeUtil.printArea(rect); // 面积为:24.00 + ShapeUtil.printArea(tri); // 面积为:12.00 + } +} diff --git a/w5/Rectangle.java b/w5/Rectangle.java new file mode 100644 index 0000000..5674664 --- /dev/null +++ b/w5/Rectangle.java @@ -0,0 +1,14 @@ +public 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; + } +} diff --git a/w5/Shape.java b/w5/Shape.java new file mode 100644 index 0000000..7485c71 --- /dev/null +++ b/w5/Shape.java @@ -0,0 +1,4 @@ +public abstract class Shape { + // 抽象方法:没有方法体,强制子类必须实现 + public abstract double getArea(); +} diff --git a/w5/ShapeUtil.java b/w5/ShapeUtil.java new file mode 100644 index 0000000..02fa8ce --- /dev/null +++ b/w5/ShapeUtil.java @@ -0,0 +1,6 @@ +public class ShapeUtil { + // 参数类型是Shape,传Circle/Rectangle/Triangle都可以 → 这就是多态! + public static void printArea(Shape shape) { + System.out.printf("面积为:%.2f%n", shape.getArea()); + } +} diff --git a/w5/Triangle.java b/w5/Triangle.java new file mode 100644 index 0000000..d81b1c5 --- /dev/null +++ b/w5/Triangle.java @@ -0,0 +1,14 @@ +public 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; + } +}