定义一个接口Shap2D,使用该接口实现二维几何图形类Circle(圆形)和Rectangle(矩形)面积的计算,编写实现接口的类以及测试类。
时间: 2024-10-25 15:14:50 浏览: 36
在Java中,我们可以首先定义一个`Shap2D`接口,它包含一个计算面积的方法`getArea()`,然后分别创建`Circle`和`Rectangle`类来实现这个接口,并提供各自的面积计算逻辑。接下来是一个简单的示例:
```java
// Shap2D 接口
public interface Shap2D {
double getArea();
}
// Circle 类实现 Shap2D 接口
public class Circle implements Shap2D {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
// Rectangle 类实现 Shap2D 接口
public class Rectangle implements Shap2D {
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;
}
}
// 测试类 TestShape2D
public class TestShape2D {
public static void main(String[] args) {
Circle circle = new Circle(5);
Rectangle rectangle = new Rectangle(4, 6);
System.out.println("Circle area: " + circle.getArea());
System.out.println("Rectangle area: " + rectangle.getArea());
// 测试集合,证明多态性
Shap2D[] shapes = {circle, rectangle};
for (Shap2D shape : shapes) {
System.out.println(shape.getClass().getSimpleName() + " area: " + shape.getArea());
}
}
}
```
在这个例子中,`TestShape2D`测试类展示了如何使用`Circle`和`Rectangle`对象,并通过`Shap2D`接口调用它们的`getArea()`方法。这体现了多态性,因为尽管我们传递的是`Circle`或`Rectangle`类型的引用,但由于实现了相同的接口,所以可以统一处理。
阅读全文
相关推荐
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)