Java Reference
In-Depth Information
Itisusuallynotagoodideatodirectlyinitializeanobject'sinstancefields,andyou
will learn why when I discuss information hiding (later in this chapter). Instead, you
should perform this initialization in the class's constructor(s)—see Listing 2-6 .
Listing 2-6. Initializing Car 's instance fields via constructors
class Car
{
String make;
String model;
int numDoors;
Car(String make, String model)
{
this(make, model, 4);
}
Car(String make, String model, int nDoors)
{
this.make = make;
this.model = model;
numDoors = nDoors;
}
public static void main(String[] args)
{
Car myCar = new Car("Toyota", "Camry");
Car yourCar = new Car("Mazda", "RX-8", 2);
}
}
Listing 2-6 ' s Car class declares Car(String make, String model) and
Car(String make, String model, int nDoors) constructors. The first
constructor lets you specify the make and model, whereas the second constructor lets
you specify values for the three instance fields.
Thefirstconstructorexecutes this(make, model, 4); topassthevaluesofits
make and model parameters,alongwithadefaultvalueof 4 tothesecondconstructor.
Doing so demonstrates an alternative to explicitly initializing an instance field, and is
preferable from a code maintenance perspective.
 
Search WWH ::




Custom Search