Java Reference
In-Depth Information
this.make = make;
this.model = model;
this.numDoors = numDoors;
public static void main(String[] args)
Car myCar = new Car("Toyota", "Camry");
Car yourCar = new Car("Mazda", "RX-8", 2);
Listing 2-7 's static prefix implies that there is only one copy of the counter
tializedtodefaultzerovalues.Forexample, counter isinitialized to 0 .(Aswithin-
time an object is created, counter will increase by 1 thanks to the counter++ ex-
pressioninthe Car(String make, String model, int numDoors) con-
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
Search WWH ::

Custom Search