定义Rectangle类,使其具有以下软件接口: class Rectangle { public Rectangle(); //将矩形的宽和高均设为1 public Rectangle (int w, int h) ; public Rectangle(Rectangler); //用的状态设置当前长方形的状态 public double getArea(); //计算矩形的面积 public double getPerimeter();//计算矩形的周长 public boolean equals(Rectangle r);/测试当前矩形与参数矩形r的面积是否相等 public int getwidth (); //返回矩形的宽 publicint getHeight(); //返回矩形的高 public String tostring(); //以格式“矩形(w,h)”返回当前矩形的长与宽的字符串表示。 然后再编写main方法进行测试,主要测试构造方法和toString方法
时间: 2023-05-12 11:04:28 浏览: 158
按以下描述和要求建立两个类:基类 Rectangle(矩形类) 和派生类 Cube(正方体)
好的,以下是Rectangle类的代码:
```
public class Rectangle {
private int width;
private int height;
public Rectangle() {
this.width = 1;
this.height = 1;
}
public Rectangle(int w, int h) {
this.width = w;
this.height = h;
}
public Rectangle(Rectangle r) {
this.width = r.width;
this.height = r.height;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
public boolean equals(Rectangle r) {
return this.getArea() == r.getArea();
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public String toString() {
return "矩形(" + width + ", " + height + ")";
}
}
```
接下来是测试代码:
```
public class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle(3, 4);
Rectangle r3 = new Rectangle(r2);
System.out.println(r1.toString());
System.out.println(r2.toString());
System.out.println(r3.toString());
System.out.println("r1的面积为:" + r1.getArea());
System.out.println("r2的周长为:" + r2.getPerimeter());
System.out.println("r3和r2的面积是否相等:" + r3.equals(r2));
}
}
```
输出结果为:
```
矩形(1, 1)
矩形(3, 4)
矩形(3, 4)
r1的面积为:1.0
r2的周长为:14.0
r3和r2的面积是否相等:true
```
希望这个答案能够帮到你!
阅读全文