1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
|
public class Rectangle {
private double width;
private double height;
/** create a Rectangle with given height and width */
public Rectangle(double width, double height) {
/* width is a member variable name,
to avoid confusion, we use this */
this.width = width;
this.height = height;
}
/** create a sqare with the given width */
public Rectangle(double width) {
/* this is another usage of this:
we use it to call another constructor
it is same as
this.width = width;
this.height = width */
this(width, width);
}
/** find out the perimeter of the rectangle */
public double perimeter() {
/* you can access the member variables */
return 2*(height + width);
}
/** find out the area of the rectangle */
public double area() {
return height*width;
}
/** return the ratio of the area to the perimeter */
public double areaToPerimeterRatio() {
/* you can access the methods */
return area()/perimeter();
}
/** multiply the rectange by x times */
public void multiply(int x) {
/* you can change the members width, height */
width*=x;
height*=x;
}
/** the function returns true if it can be contained in anther Rectangle */
public boolean containedIn(Rectangle rect) {
/* you can access the members of other rectangle */
return height <= rect.height && width <= rect.width;
}
/** return the string representation of the class */
public String toString() {
/* toString method is used by System.out.println method
to print out the object. */
return "height : " + height + ", " + "width: " + width;
}
}
|