1 changed files with 70 additions and 0 deletions
@ -0,0 +1,70 @@ |
|||
// Shape.java
|
|||
public abstract class Shape { |
|||
public abstract double getArea(); |
|||
} |
|||
|
|||
// 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; |
|||
} |
|||
} |
|||
|
|||
// Rectangle.java
|
|||
public class Rectangle extends Shape { |
|||
private double length; |
|||
private double width; |
|||
|
|||
public Rectangle(double length, double width) { |
|||
this.length = length; |
|||
this.width = width; |
|||
} |
|||
|
|||
@Override |
|||
public double getArea() { |
|||
return length * width; |
|||
} |
|||
} |
|||
|
|||
// Triangle.java
|
|||
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; |
|||
} |
|||
} |
|||
|
|||
// ShapeUtil.java
|
|||
public class ShapeUtil { |
|||
public static void printArea(Shape shape) { |
|||
System.out.printf("图形面积:%.2f\n", shape.getArea()); |
|||
} |
|||
} |
|||
|
|||
// Demo.java(测试类,展示多态)
|
|||
public class Demo { |
|||
public static void main(String[] args) { |
|||
Shape circle = new Circle(5.0); |
|||
Shape rectangle = new Rectangle(4.0, 6.0); |
|||
Shape triangle = new Triangle(3.0, 4.0); |
|||
|
|||
ShapeUtil.printArea(circle); // 图形面积:78.54
|
|||
ShapeUtil.printArea(rectangle); // 图形面积:24.00
|
|||
ShapeUtil.printArea(triangle); // 图形面积:6.00
|
|||
} |
|||
} |
|||
Loading…
Reference in new issue