Java Reference
In-Depth Information
{
this.make = make;
this.model = model;
this.numDoors = numDoors;
counter++;
}
public static void main(String[] args)
{
Car myCar = new Car("Toyota", "Camry");
Car yourCar = new Car("Mazda", "RX-8", 2);
System.out.println(Car.counter);
}
}
Listing 2-7 's static prefix implies that there is only one copy of the counter
field,notonecopyperobject.Whenaclassisloadedintomemory,classfieldsareini-
tializedtodefaultzerovalues.Forexample, counter isinitialized to 0 .(Aswithin-
stancefields,youcanalternativelyassignavaluetoaclassfieldinitsdeclaration.)Each
time an object is created, counter will increase by 1 thanks to the counter++ ex-
pressioninthe Car(String make, String model, int numDoors) con-
structor.
Unlikeinstancefields,classfieldsarenormallyaccesseddirectlyviathememberac-
cess operator. Although you could access a class field via an object reference (as in
myCar.counter ),itisconventionaltoaccessaclassfieldbyusingtheclass'sname,
as in Car.counter . (It is also easier to tell that the code is accessing a class field.)
Note Because the main() method is a member of Listing 2-7 's Car class, you
could access counter directly, as in System.out.println(counter); . To
access counter in the context of another class's main() method, however, you
would have to specify Car.counter .
Ifyourun Listing2-7 , youwillnoticethatitoutputs 2 ,becausetwo Car objectshave
been created.
Declaring Read-Only Instance and Class Fields
The previously declared fields can be written to as well as read from. However, you
mightwanttodeclareafieldthatisread-only;forexample,afieldthatnamesaconstant
Search WWH ::




Custom Search