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.

61 lines
1.5 KiB

abstract class Shape {//定义一个抽象类
public abstract double getArea();//强制所有图形都必须能计算面积
}
// 圆形
class Circle extends Shape {//继承shape,必须实现getarea
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 length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double getArea() {
return length * width;
}
}
// 三角形
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;
}
}
// 工具类
class ShapeUtil {//专门用来打印图形面积
public static void printArea(Shape shape) {//任意接受一个图形
System.out.println("图形面积:" + shape.getArea());
}
}