1)编写接口“形状”,在其中定义静态常量PI,其值为双精度值 3.14,定义抽象方法“计算面积”“计算周长” 2)编写“形状”接口的实现类圆、长方形、三角形(属性包含底边与高) 3)编写测试类,分别创建一到两个长方形对象、圆形对象、三角形对象,计算并打印它们各自的面积和周长
时间: 2024-09-22 22:07:06 浏览: 43
首先,我们来定义一个名为`Shape`的接口,它包含静态常量`PI`和两个抽象方法:
```java
public interface Shape {
static final double PI = 3.14;
// 抽象方法
abstract double calculateArea();
abstract double calculatePerimeter();
}
```
接下来,我们会为这个接口提供三个具体的实现类:Circle、Rectangle 和 Triangle。
1. `Circle` 类:
```java
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return PI * Math.pow(radius, 2);
}
@Override
public double calculatePerimeter() {
return 2 * PI * radius;
}
}
```
2. `Rectangle` 类:
```java
public class Rectangle implements Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double calculateArea() {
return width * height;
}
@Override
public double calculatePerimeter() {
return 2 * (width + height);
}
}
```
3. `Triangle` 类:
```java
public class Triangle implements Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double calculateArea() {
return 0.5 * base * height; // 假设这是一个等腰三角形,如果是其他类型的三角形,这里需要修改
}
@Override
public double calculatePerimeter() {
// 等腰三角形示例,实际计算取决于类型
return base + base + Math.sqrt(Math.pow(base / 2, 2) + Math.pow(height, 2));
}
}
```
最后,我们可以编写一个测试类`TestShapes`来创建和操作这些形状对象:
```java
public class TestShapes {
public static void main(String[] args) {
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 6);
Shape triangle = new Triangle(3, 4);
System.out.println("Circle Area: " + circle.calculateArea());
System.out.println("Circle Perimeter: " + circle.calculatePerimeter());
System.out.println("Rectangle Area: " + rectangle.calculateArea());
System.out.println("Rectangle Perimeter: " + rectangle.calculatePerimeter());
System.out.println("Triangle Area: " + triangle.calculateArea());
System.out.println("Triangle Perimeter: " + triangle.calculatePerimeter());
}
}
```
阅读全文