(矩形类 Rectangle)遵照9.2节中 Circle 类的例子,设计一个名为 Rectangle 的类表示矩形。
这个类包括:
- 两个名为 width 和 height 的 double 型数据域,它们分别表示矩形的宽和高。width 和 height 的默认值都为1。
- 创建默认矩形的无参构造方法
- 一个创建 width 和 height 为指定值的矩形的构造方法。
- 一个名为 getArea() 的方法返回这个矩形的面积。
- 一个名为 getPerimeter() 的方法返回周长。
画出该矩形的 UML 图并实现这个类。编写一个测试程序,创建两个 Rectangle 对象——一个矩形的宽为 4 而高为 40,另一个矩形的宽为 3.5 而高为 35.9 。按照这个顺序显示每个矩形的宽、高、面积、周长。
程序代码:
public class Rectangle {
private double width;
private double height;
public Rectangle(){
width=1.0;
height=1.0;
}
public Rectangle(double width,double height) {
this.width=width;
this.height=height;
}
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
public double getArea() {
return width*height;
}
public double getPerimeter() {
return 2*(width+height);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Rectangle t1=new Rectangle(4,40);
Rectangle t2=new Rectangle(3.5,35.9);
System.out.println("width:"+t1.getWidth()+" height:"+t1.getHeight()
+" Area:"+t1.getArea()+" Per:"+t1.getPerimeter());
System.out.println("width:"+t2.getWidth()+" height:"+t2.getHeight()
+" Area:"+t2.getArea()+" Per:"+t2.getPerimeter());
}
}
运行结果:
width:4.0 height:40.0 Area:160.0 Per:88.0
width:3.5 height:35.9 Area:125.64999999999999 Per:78.8