写一个抽象父类shape,有抽象方法area(求面积),perimeter(求周长),子类有等边三角形,梯形,正方形,求出这三个面积周长
时间: 2024-10-22 21:12:01 浏览: 45
首先,我们创建一个名为`Shape`的抽象父类,它包含两个抽象方法`area()`和`perimeter()`:
```java
public abstract class Shape {
protected double side; // 等边三角形的边长
public abstract double area();
public abstract double perimeter();
// 构造函数示例,用于设置等边三角形的边长
public Shape(double side) {
this.side = side;
}
}
```
接下来,我们定义三个具体的子类:`EquilateralTriangle`(等边三角形),`Trapezoid`(梯形)和`Square`(正方形):
```java
public class EquilateralTriangle extends Shape {
@Override
public double area() {
return Math.sqrt(3) / 4 * Math.pow(side, 2);
}
@Override
public double perimeter() {
return 3 * side;
}
}
public class Trapezoid extends Shape {
private double base1, base2; // 梯形的两底
public Trapezoid(double base1, double base2, double height) {
super(base1 + base2); // 周长基于两底之和
this.base1 = base1;
this.base2 = base2;
}
@Override
public double area() {
return (base1 + base2) * height / 2;
}
@Override
public double perimeter() {
return base1 + base2 + 2 * side; // 假设梯形的高已知,side为其他边长
}
}
public class Square extends Shape {
private double side;
public Square(double side) {
super(side);
this.side = side;
}
@Override
public double area() {
return Math.pow(side, 2);
}
@Override
public double perimeter() {
return 4 * side;
}
}
```
现在你可以通过创建每个子类的实例并调用它们的`area()`和`perimeter()`方法来获取各个形状的面积和周长:
```java
public class Main {
public static void main(String[] args) {
EquilateralTriangle triangle = new EquilateralTriangle(5);
System.out.println("等边三角形的面积: " + triangle.area());
System.out.println("等边三角形的周长: " + triangle.perimeter());
Trapezoid trapezoid = new Trapezoid(3, 7, 4);
System.out.println("梯形的面积: " + trapezoid.area());
System.out.println("梯形的周长: " + trapezoid.perimeter());
Square square = new Square(4);
System.out.println("正方形的面积: " + square.area());
System.out.println("正方形的周长: " + square.perimeter());
}
}
```
阅读全文