diff --git a/W4/Circle.java b/W4/Circle.java new file mode 100644 index 0000000..439826e --- /dev/null +++ b/W4/Circle.java @@ -0,0 +1,14 @@ +// 文件名:Circle.java +public class Circle extends Shape { + private double radius; // 半径 + + public Circle(double radius) { + this.radius = radius; + } + + // 实现父类的抽象方法 + @Override + public double getArea() { + return Math.PI * radius * radius; + } +} \ No newline at end of file diff --git a/W4/Main.java b/W4/Main.java new file mode 100644 index 0000000..b8ccf8a --- /dev/null +++ b/W4/Main.java @@ -0,0 +1,21 @@ +// 文件名:Main.java +public class Main { + public static void main(String[] args) { + // 创建具体图形对象 + Shape c = new Circle(5); + Shape r = new Rectangle(4, 6); + Shape t = new Triangle(3, 8); + + // 使用工具类统一处理 + ShapeUtil util = new ShapeUtil(); + + System.out.print("圆形 -> "); + util.printArea(c); + + System.out.print("矩形 -> "); + util.printArea(r); + + System.out.print("三角形 -> "); + util.printArea(t); + } +} \ No newline at end of file diff --git a/W4/Rectangle.java b/W4/Rectangle.java new file mode 100644 index 0000000..a709d9e --- /dev/null +++ b/W4/Rectangle.java @@ -0,0 +1,15 @@ +// 文件名:Rectangle.java +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; + } +} \ No newline at end of file diff --git a/W4/Shape.java b/W4/Shape.java new file mode 100644 index 0000000..1bf1ebf --- /dev/null +++ b/W4/Shape.java @@ -0,0 +1,4 @@ +public abstract class Shape { + public abstract double getArea(); + +} diff --git a/W4/ShapeUtil.java b/W4/ShapeUtil.java new file mode 100644 index 0000000..ad815b6 --- /dev/null +++ b/W4/ShapeUtil.java @@ -0,0 +1,5 @@ +public class ShapeUtil { + public void printArea(Shape shape) { + System.out.println("该图形的面积是: " + shape.getArea()); + } +}