写一个名为Rectangle的类表示矩形。其属性包括宽width、高height和颜色color,width和height都是double型的,而color则是String类型的。要求该类具有: (1) 使用构造函数完成各属性的初始赋值 (2) 使用getter和setter的形式完成属性的访问及修改 (3) 提供计算面积的getArea()方法 (4) 重写toString()方法,输出矩形信息 (5) 自己增加与Rectangle类相关的方法
时间: 2024-02-12 17:06:21 浏览: 35
好的,我会为您解答这个问题。
以下是实现Rectangle类的Java代码:
```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;
}
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;
}
@Override
public String toString() {
return "Rectangle [width=" + width + ", height=" + height + ", color=" + color + "]";
}
public boolean isSquare() {
return width == height;
}
}
```
在这个类中,我们定义了三个属性width、height和color,并在构造函数中初始化它们。我们还提供了getter和setter方法来访问和修改这些属性。另外,我们实现了一个计算面积的getArea()方法和重写了toString()方法来输出矩形的信息。
最后,我们还添加了一个名为isSquare()的方法,用于判断矩形是否为正方形。
希望这个例子对您有所帮助!
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)