Java Reference
In-Depth Information
Declaring and Accessing Instance Fields
You can declare an instance field by minimally specifying a type name, followed by
presents a
Car
class with three instance field declarations.
Listing 2-3.
Declaring a
Car
class with
make
,
model
, and
numDoors
instance fields
class Car
{
String make;
String model;
int numDoors;
}
declaresan
int
instancefieldnamed
numDoors
.Byconvention,afield'snamebegins
withalowercaseletter,andthefirstletterofeachsubsequentwordinamultiwordfield
name is capitalized.
Whenanobjectiscreated,instancefieldsareinitializedtodefaultzerovalues,which
youinterpretatthesourcecodelevelasliteralvalue
false
,
'\u0000'
,
0
,
0L
,
0.0
,
0.0F
, or
null
(depending on element type). For example, if you were to execute
Car car = new Car();
,
make
and
model
would be initialized to
null
and
numDoors
would be initialized to
0
.
Youcanassignvaluestoorreadvaluesfromanobject'sinstancefieldsbyusingthe
member access operator (
.
); the left operand specifies the object's reference and the
rightoperandspecifiestheinstancefieldtobeaccessed.
Listing2-4
usesthisoperatorto
initialize a
Car
object's
make
,
model
, and
numDoors
instance fields.
Listing 2-4.
Initializing a
Car
object's instance fields
class Car
{
String make;
String model;
int numDoors;
public static void main(String[] args)
{
Car car = new Car();