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.
51 lines
1.3 KiB
51 lines
1.3 KiB
abstract class Shape {
|
|
public abstract double getArea();
|
|
}
|
|
class Circle extends Shape {
|
|
private double radius;
|
|
public Circle(double radius) {
|
|
this.radius = radius;
|
|
}
|
|
@Override
|
|
public double getArea() {
|
|
return Math.PI * radius * radius;
|
|
}
|
|
}
|
|
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;
|
|
}
|
|
}
|
|
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;
|
|
}
|
|
}
|
|
public class ShapeUtil {
|
|
public static void printArea(Shape shape) {
|
|
System.out.println("面积:" + shape.getArea());
|
|
}
|
|
public static void main(String[] args) {
|
|
Shape circle = new Circle(6);
|
|
Shape rectangle = new Rectangle(9, 10);
|
|
Shape triangle = new Triangle(5, 10);
|
|
printArea(circle);
|
|
printArea(rectangle);
|
|
printArea(triangle);
|
|
}
|
|
}
|
|
|