Java Reference
In-Depth Information
For example, consider a simple class that defines a circle using the (x,y) coordinate of its
center and the length of its radius. The class,
Circle
, could have two constructors: one
where the radius is defined and one where the radius is set to a default value of
1
:
class Circle {
int x, y, radius;
Circle(int xPoint, int yPoint, int radiusLength) {
this.x = xPoint;
this.y = yPoint;
this.radius = radiusLength;
}
Circle(int xPoint, int yPoint) {
this(xPoint, yPoint, 1);
}
}
The second constructor in
Circle
takes only the x and y coordinates of the circle's cen-
ter. Because no radius is defined, the default value of
1
is used—the first constructor is
called with the arguments
xPoint
,
yPoint
, and the integer literal 1.
Overloading Constructor Methods
Like regular methods, constructor methods also can take varying numbers and types of
parameters. This capability enables you to create an object with exactly the properties
you want it to have or lets the object calculate properties from different kinds of input.
For example, the
buildBox()
methods that you defined in the
Box
class earlier today
would make excellent constructor methods because they are being used to initialize an
object's instance variables to the appropriate values. So instead of the original
buildBox()
method that you defined (which took four parameters for the coordinates of
the corners), you could create a constructor.
Listing 5.6 shows a new class,
Box2
, that has the same functionality of the original
Box
class, except that it uses overloaded constructor methods instead of overloaded
buildBox()
methods.
LISTING 5.6
The Full Text of
Box2.java
1: import java.awt.Point;
2:
3: class Box2 {
4: int x1 = 0;
5: int y1 = 0;
6: int x2 = 0;