Compare commits
3 Commits
65f706f97e
...
674fddb273
| Author | SHA1 | Date |
|---|---|---|
|
|
674fddb273 | 3 weeks ago |
|
|
c595be519a | 3 weeks ago |
|
|
a07adadc11 | 3 weeks ago |
6 changed files with 63 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()); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,14 @@ |
|||||
|
public 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; |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue