5 changed files with 82 additions and 0 deletions
@ -0,0 +1,14 @@ |
|||||
|
public class Circle extends Shape { |
||||
|
private double radius; |
||||
|
|
||||
|
public Circle(double radius) { |
||||
|
this.radius = radius; |
||||
|
} |
||||
|
|
||||
|
public double getRadius() { return radius; } |
||||
|
|
||||
|
@Override |
||||
|
public double getArea() { |
||||
|
return Math.PI * radius * radius; |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,21 @@ |
|||||
|
public class Main { |
||||
|
public static void main(String[] args) { |
||||
|
// 创建图形对象
|
||||
|
Shape circle = new Circle(5.0); |
||||
|
Shape rectangle = new Rectangle(4.0, 6.0); |
||||
|
Shape triangle = new Triangle(3.0, 8.0); |
||||
|
|
||||
|
// 存入数组,统一处理(多态)
|
||||
|
Shape[] shapes = { circle, rectangle, triangle }; |
||||
|
|
||||
|
System.out.println("===== 图形面积计算器 ====="); |
||||
|
for (Shape s : shapes) { |
||||
|
ShapeUtil.printArea(s); |
||||
|
} |
||||
|
|
||||
|
System.out.println(); |
||||
|
Shape largest = ShapeUtil.findLargest(shapes); |
||||
|
System.out.println("面积最大的图形是:" + largest.getName() |
||||
|
+ "(面积 = " + String.format("%.2f", largest.getArea()) + ")"); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,17 @@ |
|||||
|
public class Rectangle extends Shape { |
||||
|
private double width; |
||||
|
private double height; |
||||
|
|
||||
|
public Rectangle(double width, double height) { |
||||
|
this.width = width; |
||||
|
this.height = height; |
||||
|
} |
||||
|
|
||||
|
public double getWidth() { return width; } |
||||
|
public double getHeight() { return height; } |
||||
|
|
||||
|
@Override |
||||
|
public double getArea() { |
||||
|
return width * height; |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,9 @@ |
|||||
|
public abstract class Shape { |
||||
|
// 抽象方法:计算面积,子类必须实现
|
||||
|
public abstract double getArea(); |
||||
|
|
||||
|
// 通用方法:返回图形名称(子类可重写)
|
||||
|
public String getName() { |
||||
|
return this.getClass().getSimpleName(); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,21 @@ |
|||||
|
public class ShapeUtil { |
||||
|
/** |
||||
|
* 统一打印任意图形的面积(多态调用) |
||||
|
*/ |
||||
|
public static void printArea(Shape shape) { |
||||
|
System.out.printf("%s 的面积为:%.2f%n", shape.getName(), shape.getArea()); |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* 找出面积最大的图形 |
||||
|
*/ |
||||
|
public static Shape findLargest(Shape[] shapes) { |
||||
|
Shape largest = shapes[0]; |
||||
|
for (Shape s : shapes) { |
||||
|
if (s.getArea() > largest.getArea()) { |
||||
|
largest = s; |
||||
|
} |
||||
|
} |
||||
|
return largest; |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue