5 changed files with 59 additions and 0 deletions
@ -0,0 +1,14 @@ |
|||
// 文件名:Circle.java
|
|||
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,21 @@ |
|||
// 文件名:Main.java
|
|||
public class Main { |
|||
public static void main(String[] args) { |
|||
// 创建具体图形对象
|
|||
Shape c = new Circle(5); |
|||
Shape r = new Rectangle(4, 6); |
|||
Shape t = new Triangle(3, 8); |
|||
|
|||
// 使用工具类统一处理
|
|||
ShapeUtil util = new ShapeUtil(); |
|||
|
|||
System.out.print("圆形 -> "); |
|||
util.printArea(c); |
|||
|
|||
System.out.print("矩形 -> "); |
|||
util.printArea(r); |
|||
|
|||
System.out.print("三角形 -> "); |
|||
util.printArea(t); |
|||
} |
|||
} |
|||
@ -0,0 +1,15 @@ |
|||
// 文件名:Rectangle.java
|
|||
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,5 @@ |
|||
public class ShapeUtil { |
|||
public void printArea(Shape shape) { |
|||
System.out.println("该图形的面积是: " + shape.getArea()); |
|||
} |
|||
} |
|||
Loading…
Reference in new issue