Java Reference
In-Depth Information
public Point(int x, int y) {
this.x = x;
this.y = y;
}
Of course, you can avoid this situation by naming parameters and local variables
differently from fields. However, some programmers prefer the style in which a vari-
able takes the same name as a closely related field, because it saves them from hav-
ing to concoct separate parameter names like initialX or newY .
In most cases, the compiler will not allow two variables to have the same name at
the same point in a program. Fields are a special case that present the risk of shadow-
ing. Java's designers decided to allow this risk so that parameter names could match
their related fields.
Multiple Constructors
A class can have multiple constructors to provide multiple ways for clients to con-
struct objects of that class. Each constructor must have a different signature (i.e.,
number and type of parameters).
Our existing Point constructor requires two parameters (the Point object's initial
x - and y -coordinates). Before we added the constructor, we were able to construct
Point objects at (0, 0) without any parameters. When a class does not have a con-
structor, Java provides a parameterless default constructor that initializes all of the
new object's fields to a zero-equivalent value. But when we added our two-parameter
constructor, we lost the default constructor. This is unfortunate, because the default
provided a useful shorter notation for constructing a Point at the origin. We can
restore this ability by adding a second, parameterless constructor to our Point class.
Our new constructor looks like this:
// constructs a Point object with location (0, 0)
public Point() {
x = 0;
y = 0;
}
Now it's possible to construct Point s in two ways:
Point p1 = new Point(5, -2); // (5, -2)
Point p2 = new Point(); // (0, 0)
Returning to the analogy of purchasing cars, you can imagine that some customers
wish to specify many details about their new cars (e.g., “I'd like a yellow Civic with gold
trim, upgraded stereo system, and a sun roof ”), while other customers wish to specify
fewer details and want the car to contain default options instead. Having multiple con-
structors gives clients similar flexibility when they ask for new objects of your class.
 
Search WWH ::




Custom Search