Browse Source

添加W3

main
故春 3 weeks ago
commit
a7ac3da214
  1. 12
      W3/Circle.java
  2. BIN
      W3/QQ20260327-221432.png
  3. 14
      W3/Rectangle.java
  4. 4
      W3/Shape.java
  5. 9
      W3/ShapeUtil.java
  6. 18
      W3/Test.java
  7. 15
      W3/Triangle.java
  8. 0
      W3/W3.txt
  9. 2
      desktop.ini

12
W3/Circle.java

@ -0,0 +1,12 @@
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}

BIN
W3/QQ20260327-221432.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 191 KiB

14
W3/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;
}
}

4
W3/Shape.java

@ -0,0 +1,4 @@
public abstract class Shape {
// 抽象方法:计算图形面积
public abstract double getArea();
}

9
W3/ShapeUtil.java

@ -0,0 +1,9 @@
public class ShapeUtil {
public static void printArea(Shape shape) {
if (shape == null) {
System.out.println("图形对象不能为空!");
return;
}
System.out.printf("图形面积为:%.2f%n", shape.getArea());
}
}

18
W3/Test.java

@ -0,0 +1,18 @@
public class Test {
public static void main(String[] args) {
// 创建不同图形对象
Shape circle = new Circle(3);
Shape rect = new Rectangle(4, 5);
Shape triangle = new Triangle(3, 4, 5);
// 统一调用工具类打印面积
System.out.println("圆形:");
ShapeUtil.printArea(circle);
System.out.println("矩形:");
ShapeUtil.printArea(rect);
System.out.println("三角形:");
ShapeUtil.printArea(triangle);
}
}

15
W3/Triangle.java

@ -0,0 +1,15 @@
public class Triangle extends Shape {
private double a, b, c;
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public double getArea() {
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
}

0
W3/W3.txt

2
desktop.ini

@ -0,0 +1,2 @@
[LocalizedFileNames]
QQ20260327-221432.png=@QQ20260327-221432.png,0
Loading…
Cancel
Save