Java Reference
In-Depth Information
You can overload buildBox() by creating a second version of the method with an argu-
ment list that takes two Point objects:
Box buildBox(Point topLeft, Point bottomRight) {
x1 = topLeft.x;
y1 = topLeft.y;
x2 = bottomRight.x;
y2 = bottomRight.y;
return this;
}
For the preceding method to work, the java.awt.Point class must be imported so that
the Java compiler can find it.
Another possible way to define the rectangle is to use a top corner, a height, and a width:
Box buildBox(Point topLeft, int w, int h) {
x1 = topLeft.x;
y1 = topLeft.y;
x2 = (x1 + w);
y2 = (y1 + h);
return this;
}
To finish this example, a printBox() is created to display the rectangle's coordinates,
and a main() method tries everything out. Listing 5.5 shows the completed class defini-
tion.
LISTING 5.5
The Full Text of Box.java
1: import java.awt.Point;
2:
3: class Box {
4: int x1 = 0;
5: int y1 = 0;
6: int x2 = 0;
7: int y2 = 0;
8:
9: Box buildBox(int x1, int y1, int x2, int y2) {
10: this.x1 = x1;
11: this.y1 = y1;
12: this.x2 = x2;
13: this.y2 = y2;
14: return this;
15: }
16:
17: Box buildBox(Point topLeft, Point bottomRight) {
18: x1 = topLeft.x;
Search WWH ::




Custom Search