commit
a7ac3da214
9 changed files with 74 additions and 0 deletions
@ -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; |
||||
|
} |
||||
|
} |
||||
|
After Width: | Height: | Size: 191 KiB |
@ -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; |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,4 @@ |
|||||
|
public abstract class Shape { |
||||
|
// 抽象方法:计算图形面积
|
||||
|
public abstract double getArea(); |
||||
|
} |
||||
@ -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()); |
||||
|
} |
||||
|
} |
||||
@ -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); |
||||
|
} |
||||
|
} |
||||
@ -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,0 +1,2 @@ |
|||||
|
[LocalizedFileNames] |
||||
|
QQ20260327-221432.png=@QQ20260327-221432.png,0 |
||||
Loading…
Reference in new issue