Java Reference
In-Depth Information
The Car(String make, String model, int numDoors) constructor
demonstrates another use for keyword this . Specifically, it demonstrates a scenario
where constructor parameters have the same names as the class's instance fields. Pre-
fixingavariablenamewith“ this. ”causestheJavacompilertocreatebytecodethat
accesses the instance field. For example, this.make = make; assigns the make
parameter's String objectreferencetothis(thecurrent) Car object's make instance
field. If make = make; was specified instead, it would accomplish nothing by as-
signing make 'svaluetoitself;aJavacompilermightnotgeneratecodetoperformthe
unnecessary assignment. In contrast, “ this. ” isn't necessary for the numDoors =
nDoors; assignment, which initializes the numDoors field from the nDoors para-
meter value.
Declaring and Accessing Class Fields
For example, suppose you want to track the number of Car objects that have been
created, and introduce a counter instance field (initialized to 0) into this class. You
also place code in the class's constructor that increases counter 's value by 1 when
an object is created. However, because each object has its own copy of the counter
instancefield,thisfield'svalueneveradvancespast1. Listing2-7 solvesthisproblem
by declaring counter to be a class field, by prefixing the field declaration with the
static keyword.
Listing 2-7. Adding a counter class field to Car
class Car
String make;
String model;
int numDoors;
static int counter;
Car(String make, String model)
this(make, model, 4);
Car(String make, String model, int numDoors)
Search WWH ::

Custom Search