5 changed files with 49 additions and 0 deletions
@ -0,0 +1,11 @@ |
|||
public class Main { |
|||
public static void main(String[] args) { |
|||
Shape circle = new Circle(5); |
|||
Shape rect = new Rectangle(4, 6); |
|||
Shape tri = new Triangle(3, 8); |
|||
|
|||
ShapeUtil.printArea(circle); // 面积为:78.54
|
|||
ShapeUtil.printArea(rect); // 面积为:24.00
|
|||
ShapeUtil.printArea(tri); // 面积为:12.00
|
|||
} |
|||
} |
|||
@ -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 { |
|||
// 参数类型是Shape,传Circle/Rectangle/Triangle都可以 → 这就是多态!
|
|||
public static void printArea(Shape shape) { |
|||
System.out.printf("面积为:%.2f%n", 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