You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.1 KiB
53 lines
1.1 KiB
// 抽象类 Shape
|
|
public abstract class Shape {
|
|
public abstract double getArea();
|
|
}
|
|
// Circle 类
|
|
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 类
|
|
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;
|
|
}
|
|
}
|
|
// Triangle 类
|
|
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 工具类
|
|
public class ShapeUtil {
|
|
public static void printArea(Shape shape) {
|
|
System.out.println("图形的面积是:" + shape.getArea());
|
|
}
|
|
}
|