5 changed files with 49 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; |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,13 @@ |
|||||
|
public class Main { |
||||
|
public static void main(String[] args) { |
||||
|
// 创建不同图形
|
||||
|
Shape circle = new Circle(5); |
||||
|
Shape rectangle = new Rectangle(4, 6); |
||||
|
Shape triangle = new Triangle(3, 4); |
||||
|
|
||||
|
// 统一打印面积
|
||||
|
ShapeUtil.printArea(circle); |
||||
|
ShapeUtil.printArea(rectangle); |
||||
|
ShapeUtil.printArea(triangle); |
||||
|
} |
||||
|
} |
||||
@ -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,6 @@ |
|||||
|
public class ShapeUtil { |
||||
|
// 统一打印任意图形的面积
|
||||
|
public static void printArea(Shape shape) { |
||||
|
System.out.println("图形面积 = " + shape.getArea()); |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue