Java Reference
In-Depth Information
car.make = "Toyota";
car.model = "Camry";
car.numDoors = 4;
Listing 2-4 presents a main() method that instantiates Car . The car instance's
make instance field is assigned the "Toyota" string, its model instance field is as-
signedthe "Camry" string,andits numDoors instancefieldisassignedintegerliteral
4 .(Astring'sdoublequotesdelimitastring'ssequenceofcharactersbutarenotpartof
the string.)
You can explicitly initialize an instance field when declaring that field to provide a
nonzerodefaultvalue,whichoverridesthedefaultzerovalue. Listing2-5 demonstrates
this point.
Listing 2-5. Initializing Car 's numDoors instance field to a default nonzero value
class Car
String make;
String model;
int numDoors = 4;
public static void main(String[] args)
Car johnDoeCar = new Car();
johnDoeCar.make = "Chevrolet";
johnDoeCar.model = "Volt";
Listing2-5 explicitlyinitializes numDoors to 4 becausethedeveloperhasassumed
thatmostcarsbeingmodeledbythisclasshavefourdoors.When Car isinitializedvia
the Car() constructor,thedeveloperonlyneedstoinitializethe make and model in-
stance fields for those cars that have four doors.
Search WWH ::

Custom Search