Browse Source

上传文件至 'w4'

main
Zhangxinyue 3 weeks ago
parent
commit
3d1101a0d8
  1. 23
      w4/Circle.java
  2. 29
      w4/Rectangle.java
  3. 10
      w4/Shape.java
  4. 27
      w4/ShapeCalculatorDemo.java
  5. 22
      w4/ShapeUtil.java

23
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;
}
}

29
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;
}
}

10
w4/Shape.java

@ -0,0 +1,10 @@
/**
* 图形抽象基类统一多态入口具体面积由子类实现
*/
public abstract class Shape {
/**
* @return 图形面积具体单位由子类语义决定如平方厘米
*/
public abstract double getArea();
}

27
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);
}
}
}

22
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());
}
}
Loading…
Cancel
Save