用Java抽象一个能表示水平等腰梯形的Trapezoid类,测试输出等腰梯形形状
时间: 2024-10-24 13:14:58 浏览: 23
在Java中,我们可以创建一个名为`Trapezoid`的抽象类,它代表一个水平等腰梯形。由于等腰梯形有两个相同的底边,我们还需要两个属性来存储这两个底边的长度,以及两个侧边的斜线长度。为了表示图形,我们将提供一些基本的方法如计算面积、绘制等。这里是一个简单的示例:
```java
import java.util.Scanner;
abstract class Trapezoid {
private double base1;
private double base2;
private double height;
public Trapezoid(double base1, double base2, double height) {
this.base1 = base1;
this.base2 = base2;
this.height = height;
}
// 抽象方法,子类需要实现
abstract double getPerimeter();
abstract double calculateArea();
public void draw() {
System.out.println("Drawing a trapezoidal shape with base1=" + base1 +
", base2=" + base2 +
", and height=" + height);
}
public double getBase1() {
return base1;
}
public double getBase2() {
return base2;
}
public double getHeight() {
return height;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the length of base1: ");
double base1 = scanner.nextDouble();
System.out.print("Enter the length of base2: ");
double base2 = scanner.nextDouble();
System.out.print("Enter the height: ");
double height = scanner.nextDouble();
try {
// 创建等腰梯形实例,假设SubTrapezoid是实现了Trapezoid的子类
SubTrapezoid subTrapezoid = new SubTrapezoid(base1, base2, height);
System.out.println("Perimeter: " + subTrapezoid.getPerimeter());
System.out.println("Area: " + subTrapezoid.calculateArea());
subTrapezoid.draw();
} catch (Exception e) {
System.out.println("Error creating trapezoid: " + e.getMessage());
}
scanner.close();
}
}
class SubTrapezoid extends Trapezoid {
@Override
double getPerimeter() {
return base1 + base2 + 2 * Math.sqrt(Math.pow(height / 2, 2) + (base1 - base2) * (base1 - base2) / 4);
}
@Override
double calculateArea() {
return (base1 + base2) * height / 2;
}
}
```
在这个例子中,`SubTrapezoid`类实现了`Trapezoid`的抽象方法,并提供了具体的面积和周长计算。`main`函数用于获取用户输入并创建等腰梯形实例。
阅读全文