java编写一个程序,程序包含如下内容 定义一个含计算面积和周长方法的图形接口shape(area,length) 编写实现图形接口的半圆类。 编写实现图形接口的长方体类。 主类里面去生成具体对象实现。
时间: 2023-12-03 22:47:46 浏览: 91
下面是Java代码实现:
Shape.java
```java
public interface Shape {
double calculateArea();
double calculatePerimeter();
}
```
SemiCircle.java
```java
public class SemiCircle implements Shape {
private double radius;
public SemiCircle(double radius) {
this.radius = radius;
}
public double calculateArea() {
return Math.PI * radius * radius / 2;
}
public double calculatePerimeter() {
return Math.PI * radius + 2 * radius;
}
}
```
Rectangle.java
```java
public class Rectangle implements Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double calculateArea() {
return length * width;
}
public double calculatePerimeter() {
return 2 * (length + width);
}
}
```
Main.java
```java
public class Main {
public static void main(String[] args) {
SemiCircle semiCircle = new SemiCircle(5);
System.out.println("Semi-Circle Area: " + semiCircle.calculateArea());
System.out.println("Semi-Circle Perimeter: " + semiCircle.calculatePerimeter());
Rectangle rectangle = new Rectangle(3, 4);
System.out.println("Rectangle Area: " + rectangle.calculateArea());
System.out.println("Rectangle Perimeter: " + rectangle.calculatePerimeter());
}
}
```
输出结果:
```
Semi-Circle Area: 19.634954084936208
Semi-Circle Perimeter: 17.707963267948966
Rectangle Area: 12.0
Rectangle Perimeter: 14.0
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)