2 changed files with 80 additions and 0 deletions
@ -0,0 +1,80 @@ |
|||||
|
package src.main.w5; |
||||
|
// 抽象图形类
|
||||
|
abstract class Shape { |
||||
|
public abstract double getArea(); |
||||
|
} |
||||
|
|
||||
|
// 圆形类
|
||||
|
class Circle extends Shape { |
||||
|
private double radius; |
||||
|
|
||||
|
public Circle(double radius) { |
||||
|
this.radius = radius; |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public double getArea() { |
||||
|
return Math.PI * radius * radius; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 矩形类
|
||||
|
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; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 三角形类
|
||||
|
class Triangle extends Shape { |
||||
|
private double base; |
||||
|
private double height; |
||||
|
|
||||
|
public Triangle(double base, double height) { |
||||
|
this.base = base; |
||||
|
this.height = height; |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public double getArea() { |
||||
|
return 0.5 * base * height; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 图形工具类
|
||||
|
class ShapeUtil { |
||||
|
public static void printArea(Shape shape) { |
||||
|
System.out.printf("该图形的面积为:%.2f%n", shape.getArea()); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 主程序入口
|
||||
|
public class ShapeAreaCalculator { |
||||
|
public static void main(String[] args) { |
||||
|
// 创建不同图形对象
|
||||
|
Shape circle = new Circle(2.0); |
||||
|
Shape rectangle = new Rectangle(3.0, 4.0); |
||||
|
Shape triangle = new Triangle(3.0, 4.0); |
||||
|
|
||||
|
// 统一调用工具类打印面积
|
||||
|
System.out.println("圆形:"); |
||||
|
ShapeUtil.printArea(circle); |
||||
|
|
||||
|
System.out.println("矩形:"); |
||||
|
ShapeUtil.printArea(rectangle); |
||||
|
|
||||
|
System.out.println("三角形:"); |
||||
|
ShapeUtil.printArea(triangle); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
|
||||
|
After Width: | Height: | Size: 77 KiB |
Loading…
Reference in new issue