请设计并编写一个同时满足下列所有需求的代码。 (1)定义一个public接口,接口名为Shape; (2)定义返回值为double类型并且无输入参数的public抽象方法,其中方法名为getArea; (3)定义返回值为double类型并且无输入参数的public抽象方法,其中方法名为getPerimeter。 (4)定义一个public类Square,且该类实现了接口Shape; (5)在类Square中定义两个double类型的public成员变量,其中成员变量名为:width,height; (6)用带有两个形式参数的public构造方法对Square类中的成员变量进行初始化,其中形式参数名为: width,height; (7)在Square类中对getArea方法进行实现,返回面积,即width*height; (8)在Square类中对getPerimeter方法进行实现,返回周长,即2*(width+height)。 初始样例: 3 4 输出样例: (不考虑小数位数) area = 12.0 peri = 14.0
时间: 2024-03-23 14:40:21 浏览: 20
下面是代码实现:
```java
// 定义接口 Shape
public interface Shape {
// 返回面积
public abstract double getArea();
// 返回周长
public abstract double getPerimeter();
}
// 定义 Square 类,实现 Shape 接口
public class Square implements Shape {
public double width;
public double height;
// 构造方法
public Square(double width, double height) {
this.width = width;
this.height = height;
}
// 实现 getArea 方法
public double getArea() {
return width * height;
}
// 实现 getPerimeter 方法
public double getPerimeter() {
return 2 * (width + height);
}
}
// 测试代码
public static void main(String[] args) {
double width = 3;
double height = 4;
Square square = new Square(width, height);
System.out.println("area = " + square.getArea());
System.out.println("peri = " + square.getPerimeter());
}
```
输出结果为:
```
area = 12.0
peri = 14.0
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)