创建一个图形接口类shape,包含计算周长和面积的声明方法,创建园类实现接口shape,根据半径计算圆的周长和面积,创建矩形类rectangle,根据长,宽计算矩形的周长和面积
时间: 2024-09-19 16:06:48 浏览: 101
首先,我们可以定义一个名为`Shape`的接口,用于表示所有形状的通用属性,如周长和面积的计算:
```java
public interface Shape {
double calculatePerimeter();
double calculateArea();
}
```
接着,我们创建一个`Circle`类,它是`Shape`接口的一个具体实现,用于表示圆形并提供特定的计算方法:
```java
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
@Override
public double calculateArea() {
return Math.PI * Math.pow(radius, 2);
}
}
```
对于矩形,我们可以定义一个`Rectangle`类,并同样实现`Shape`接口:
```java
public class Rectangle implements Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double calculatePerimeter() {
return 2 * (length + width);
}
@Override
public double calculateArea() {
return length * width;
}
}
```
现在,你可以创建`Circle`或`Rectangle`的对象并调用它们的`calculatePerimeter()`和`calculateArea()`方法来获取具体的周长和面积值。例如:
```java
public static void main(String[] args) {
Circle circle = new Circle(5.0);
System.out.println("Circle perimeter: " + circle.calculatePerimeter());
System.out.println("Circle area: " + circle.calculateArea());
Rectangle rectangle = new Rectangle(4.0, 6.0);
System.out.println("Rectangle perimeter: " + rectangle.calculatePerimeter());
System.out.println("Rectangle area: " + rectangle.calculateArea());
}
```
阅读全文