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.
47 lines
1.2 KiB
47 lines
1.2 KiB
public abstract class Shape {
|
|
public abstract double getArea();
|
|
}
|
|
class Circle extends Shape {
|
|
private double radius;
|
|
public Circle(double radius) {
|
|
this.radius = radius;
|
|
}
|
|
public double getArea() {
|
|
return Math.PI * radius * radius;
|
|
}
|
|
}
|
|
class Rectangle extends Shape {
|
|
private double width, height;
|
|
public Rectangle(double width, double height) {
|
|
this.width = width;
|
|
this.height = height;
|
|
}
|
|
public double getArea() {
|
|
return width * height;
|
|
}
|
|
}
|
|
class Triangle extends Shape {
|
|
private double base, height;
|
|
public Triangle(double base, double height) {
|
|
this.base = base;
|
|
this.height = height;
|
|
}
|
|
public double getArea() {
|
|
return 0.5 * base * height;
|
|
}
|
|
}
|
|
class ShapeUtil {
|
|
public static void printArea(Shape shape) {
|
|
System.out.println("面积:" + shape.getArea());
|
|
}
|
|
}
|
|
class Main {
|
|
public static void main(String[] args) {
|
|
Shape circle = new Circle(5);
|
|
Shape rect = new Rectangle(4, 6);
|
|
Shape tri = new Triangle(3, 4);
|
|
ShapeUtil.printArea(circle);
|
|
ShapeUtil.printArea(rect);
|
|
ShapeUtil.printArea(tri);
|
|
}
|
|
}
|