Java Reference
In-Depth Information
car.make = "Toyota";
car.model = "Camry";
car.numDoors = 4;
}
}
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;
Car()
{
}
public static void main(String[] args)
{
Car johnDoeCar = new Car();
johnDoeCar.make = "Chevrolet";
johnDoeCar.model = "Volt";
}
}
thatmostcarsbeingmodeledbythisclasshavefourdoors.When
Car
isinitializedvia
the
Car()
constructor,thedeveloperonlyneedstoinitializethe
make
and
model
in-
stance fields for those cars that have four doors.