声明抽象基类Shape,由它派生出5个派生类;Circle(圆形)、Square(正方形)、Rectangle(矩形)、Trapezoid(梯形)、Triangle(三角形),分别计算几种图形的面积,并求它们的和并显示出来。请按照要求选择如下一种方式编程实现。 注意圆周率取3.14.
时间: 2023-07-10 07:31:29 浏览: 108
好的,以下是使用面向对象编程实现题目要求的 Java 代码:
```java
public abstract class Shape {
public abstract double getArea();
public abstract double getPerimeter();
}
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return 3.14 * radius * radius;
}
@Override
public double getPerimeter() {
return 2 * 3.14 * radius;
}
}
public class Square extends Shape {
private double sideLength;
public Square(double sideLength) {
this.sideLength = sideLength;
}
@Override
public double getArea() {
return sideLength * sideLength;
}
@Override
public double getPerimeter() {
return 4 * sideLength;
}
}
public 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;
}
@Override
public double getPerimeter() {
return 2 * (length + width);
}
}
public class Trapezoid extends Shape {
private double upperBase;
private double lowerBase;
private double height;
private double leftSide;
private double rightSide;
public Trapezoid(double upperBase, double lowerBase, double height, double leftSide, double rightSide) {
this.upperBase = upperBase;
this.lowerBase = lowerBase;
this.height = height;
this.leftSide = leftSide;
this.rightSide = rightSide;
}
@Override
public double getArea() {
return (upperBase + lowerBase) * height / 2;
}
@Override
public double getPerimeter() {
return upperBase + lowerBase + leftSide + rightSide;
}
}
public class Triangle extends Shape {
private double base;
private double height;
private double side1;
private double side2;
public Triangle(double base, double height, double side1, double side2) {
this.base = base;
this.height = height;
this.side1 = side1;
this.side2 = side2;
}
@Override
public double getArea() {
return base * height / 2;
}
@Override
public double getPerimeter() {
return base + side1 + side2;
}
}
public class ShapeTest {
public static void main(String[] args) {
Circle circle = new Circle(5);
Square square = new Square(4);
Rectangle rectangle = new Rectangle(3, 5);
Trapezoid trapezoid = new Trapezoid(3, 5, 4, 2, 2);
Triangle triangle = new Triangle(4, 3, 5, 5);
double sumArea = circle.getArea() + square.getArea() + rectangle.getArea() + trapezoid.getArea() + triangle.getArea();
System.out.println("Sum of areas: " + sumArea);
}
}
```
在这个代码中,我们首先定义了一个抽象基类 `Shape`,其中包含了两个抽象方法 `getArea()` 和 `getPerimeter()`,用于计算形状的面积和周长。然后,我们定义了五个派生类 `Circle`、`Square`、`Rectangle`、`Trapezoid` 和 `Triangle`,分别表示圆形、正方形、矩形、梯形和三角形。这些派生类都继承自抽象基类 `Shape`,并实现了其中的抽象方法。在实现中,我们使用了相应图形的公式来计算其面积和周长。
最后,在 `ShapeTest` 类中,我们创建了五个图形的实例,并计算它们的面积之和。由于每个图形都实现了 `getArea()` 方法,因此我们可以直接调用该方法来计算其面积。最终,我们将所有图形的面积相加,并输出结果。
阅读全文