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);
}
}
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.)
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
.
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