diff --git a/w4/Circle.java b/w4/Circle.java new file mode 100644 index 0000000..729fac6 --- /dev/null +++ b/w4/Circle.java @@ -0,0 +1,22 @@ +public class Circle extends Shape{ + private double radius; + public Circle(double radius){ + if (radius <= 0){ + throw new IllegalArgumentException("半径必须大于0"); + } + this.radius = radius; + } + @Override + public double getArea() { + return Math.PI * radius * radius; + } + + @Override + public String getShapeName() { + return "圆形"; + } + + public double getRadius() { + return radius; + } +} diff --git a/w4/Main.java b/w4/Main.java new file mode 100644 index 0000000..6f3cfa2 --- /dev/null +++ b/w4/Main.java @@ -0,0 +1,13 @@ +//TIP 要运行代码,请按 或 +// 点击装订区域中的 图标。 +void main() { + //TIP 当文本光标位于高亮显示的文本处时按 + // 查看 IntelliJ IDEA 建议如何修正。 + IO.println(String.format("Hello and welcome!")); + + for (int i = 1; i <= 5; i++) { + //TIP 按 开始调试代码。我们已经设置了一个 断点 + // 但您始终可以通过按 添加更多断点。 + IO.println("i = " + i); + } +} diff --git a/w4/Rectangle.java b/w4/Rectangle.java new file mode 100644 index 0000000..48de0dc --- /dev/null +++ b/w4/Rectangle.java @@ -0,0 +1,30 @@ +public class Rectangle extends Shape{ + private double length; + private double width; + + public Rectangle(double length, double width) { + if (length <= 0 || width <= 0) { + throw new IllegalArgumentException("长和宽必须大于0"); + } + this.length = length; + this.width = width; + } + + @Override + public double getArea() { + return length * width; + } + + @Override + public String getShapeName() { + return "长方形"; + } + + public double getLength() { + return length; + } + + public double getWidth() { + return width; + } +} diff --git a/w4/Shape.java b/w4/Shape.java new file mode 100644 index 0000000..3b279df --- /dev/null +++ b/w4/Shape.java @@ -0,0 +1,5 @@ +public abstract class Shape { + public abstract double getArea(); + + public abstract String getShapeName(); +} diff --git a/w4/ShapeUtil.java b/w4/ShapeUtil.java new file mode 100644 index 0000000..c230876 --- /dev/null +++ b/w4/ShapeUtil.java @@ -0,0 +1,12 @@ +public class ShapeUtil { + public static void printArea(Shape shape) { + if (shape == null) { + System.out.println("错误:图形对象为空"); + return; + } + + System.out.println("图形类型:" + shape.getShapeName()); + System.out.println("面积:" + shape.getArea()); + System.out.println("------------------------"); + } +}