编写一个接口程序,其中定义一个计算面积的方法。然后,再设计应用程序实现这个接口,分别计算矩形两边长为4和6面积和半径为2的圆面积并输出
时间: 2024-03-03 15:47:01 浏览: 15
以下是一个 Java 代码示例,实现了一个计算面积的接口 `Shape`,并在应用程序中使用该接口计算矩形和圆形的面积:
```java
// 定义计算面积的接口
interface Shape {
double getArea();
}
// 实现矩形类,实现计算面积的接口
class Rectangle implements Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getArea() {
return length * width;
}
}
// 实现圆形类,实现计算面积的接口
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
}
// 应用程序,计算矩形和圆形的面积
public class Main {
public static void main(String[] args) {
Shape rectangle = new Rectangle(4, 6);
Shape circle = new Circle(2);
System.out.println("矩形的面积为:" + rectangle.getArea());
System.out.println("圆形的面积为:" + circle.getArea());
}
}
```
输出结果为:
```
矩形的面积为:24.0
圆形的面积为:12.566370614359172
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)