写一个名为Rectangle的类表示矩形。其属性包括宽width、高height和颜色color,width和height都是double型的,而color则是String类型的。要求该类具有: (1) 使用构造函数完成各属性的初始赋值 (2) 使用getter和setter的形式完成属性的访问及修改 (3) 提供计算面积的getArea()方法 (4) 重写toString()方法,输出矩形信息 (5) 自己增加与Rectangle类相关的方法
时间: 2024-03-26 16:34:16 浏览: 26
好的,以下是你要求的Rectangle类的代码实现:
```java
public class Rectangle {
private double width;
private double height;
private String color;
// 构造函数
public Rectangle(double width, double height, String color) {
this.width = width;
this.height = height;
this.color = color;
}
// getter和setter
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
// 计算面积
public double getArea() {
return width * height;
}
// 重写toString方法
@Override
public String toString() {
return "Rectangle{" +
"width=" + width +
", height=" + height +
", color='" + color + '\'' +
'}';
}
// 自定义方法
public double getPerimeter() {
return 2 * (width + height);
}
}
```
其中,我们定义了三个私有属性:width、height和color,用于存储矩形的宽、高和颜色。使用构造函数完成各属性的初始赋值。使用getter和setter的形式完成属性的访问及修改。提供了计算面积的getArea()方法和重写toString()方法,输出矩形信息。同时,我们自己增加了一个与Rectangle类相关的方法getPerimeter(),用于计算矩形的周长。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![exe](https://img-home.csdnimg.cn/images/20210720083343.png)