题目:
(矩形类Rectangle)
遵照9.2节中Circle类的例子,设计一个名为Rectangle的类表示矩形。这个类包括:
• 两个名为width和height的double型数据域,它们分别表示矩形的宽和高。width和height的默认值都为1。
• 创建默认矩形的无参构造方法。
• —个创建width和height为指定值的矩形的构造方法。
• 一个名为getArea()的方法返回这个矩形的面积。
• 一个名为getPerimeter()的方法返回周长。
画出该类的UML图并实现这个类。编写一个测试程序,创建两个Rectangle对象,一个矩形的宽为4而高为40,另一个矩形的宽为3.5,而高为35.9。按照这个顺序显示每个矩形的宽、高、面积和周长。
(Rectangle class)
Following the example of the Circle class in section 9.2, design a class called Rectangle to represent a rectangle. This class includes:
Two double data fields named width and height represent the width and height of the rectangle, respectively. The default values for width and height are both 1.
Create a non parametric construction method for the default rectangle.
A construction method for creating rectangles with specified width and height values.
A method called getArea() returns the area of this rectangle.
A method called getPerimeter () returns the circumference.
Draw a UML diagram of the class and implement it. Write a test program to create two Rectangle objects, one with a width of 4 and a height of 40, and the other with a width of 3.5 and a height of 35.9. Display the width, height, area, and perimeter of each rectangle in this order.
代码:
Rectangle.java
public class Rectangle {
double width;
double heigth;
Rectangle(){
width=1;
heigth=1;
}
Rectangle(double width,double heigth){
this.width=width;
this.heigth=heigth;
}
double getArea(){
return width*heigth;
}
double getPerimeter(){
return 2*(width+heigth);
}
}
Test.java
public class Test {
public static void main(String[] args) {
Rectangle r1 = new Rectangle(4, 40);
Rectangle r2 = new Rectangle(3.5, 35.9);
System.out.printf("Ractangle 1\t%.2f\t%.2f\t%.2f\t%.2f", r1.width, r1.heigth, r1.getArea(), r1.getPerimeter());
System.out.printf("\nRactangle 2\t%.2f\t%.2f\t%.2f\t%.2f", r2.width, r2.heigth, r2.getArea(), r2.getPerimeter());
}
}
UML图
//__________________________UML DIAGRAM_____________________________* /* | * Rectangle | *------------------------------------------------------------------| * width : double | * | * height : double | *------------------------------------------------------------------| * Rectangle() | * | * Rectangle(Width:double, Height:Double) | * | * getArea(): double | * | * getRectangle(): double | *__________________________________________________________________| */