定义一个abstract的Shape类,求形状的面积,由Shape类派生4个子类三角形类、矩形类、梯形类、圆形类,分别求各自面积,然后进行测试。
时间: 2024-08-05 07:00:20 浏览: 55
首先,让我们定义一个抽象的 `Shape` 类,这个类包含一个抽象方法 `getArea()`,表示所有形状的面积计算方法,因为我们需要为每个具体的形状提供实现。然后,我们将创建四个子类,每个子类都覆盖这个抽象方法并提供自己的特定面积计算逻辑。
```java
// Shape接口/抽象类
public abstract class Shape {
public abstract double getArea();
}
// 子类1: 三角形
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;
}
}
// 子类2: 矩形
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;
}
}
// 子类3: 梯形
public class Trapezoid extends Shape {
private double a;
private double b;
private double height;
public Trapezoid(double a, double b, double height) {
this.a = a;
this.b = b;
this.height = height;
}
@Override
public double getArea() {
return (a + b) * height / 2;
}
}
// 子类4: 圆形
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
```
接下来,我们可以创建一个测试类来实例化这些形状并计算它们的面积:
```java
public class Main {
public static void main(String[] args) {
Shape triangle = new Triangle(3, 4);
Shape rectangle = new Rectangle(5, 6);
Shape trapezoid = new Trapezoid(4, 5, 7);
Shape circle = new Circle(3.5);
System.out.println("Triangle area: " + triangle.getArea());
System.out.println("Rectangle area: " + rectangle.getArea());
System.out.println("Trapezoid area: " + trapezoid.getArea());
System.out.println("Circle area: " + circle.getArea());
}
}
```
阅读全文