java设计一个形状类shape圆形矩形三角形梯形
时间: 2023-12-17 14:05:26 浏览: 146
好的,以下是一个基本的Java代码,实现了Shape(形状)的抽象类和Circle(圆形)、Rectangle(矩形)、Triangle(三角形)、Trapezoid(梯形)的具体类:
```java
public abstract class Shape {
public abstract double getArea(); // 获取面积的抽象方法
}
public class Circle extends Shape {
private double radius; // 圆的半径
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
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;
}
}
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;
}
}
public class Trapezoid extends Shape {
private double top; // 梯形的上底
private double bottom; // 梯形的下底
private double height; // 梯形的高
public Trapezoid(double top, double bottom, double height) {
this.top = top;
this.bottom = bottom;
this.height = height;
}
@Override
public double getArea() {
return 0.5 * (top + bottom) * height;
}
}
```
这样,我们就可以创建Shape的子类实例来获取它们的面积了:
```java
Circle circle = new Circle(5);
double circleArea = circle.getArea(); // 获取圆的面积
Rectangle rectangle = new Rectangle(3, 4);
double rectangleArea = rectangle.getArea(); // 获取矩形的面积
Triangle triangle = new Triangle(6, 8);
double triangleArea = triangle.getArea(); // 获取三角形的面积
Trapezoid trapezoid = new Trapezoid(4, 8, 5);
double trapezoidArea = trapezoid.getArea(); // 获取梯形的面积
```
阅读全文