Java Reference
In-Depth Information
Each
Point
object is unique and has its own copy of the
x
and
y
fields.
Changing
x
in the object
lowerLeft
, for example, does not affect the
value of
x
in the object
upperRight
. The fields in objects are known as
instance variables,
because there is a unique copy of the field in each
object (instance) of the class.
When you use
new
to create an object, a special piece of code, known as
a
constructor,
is invoked to perform any initialization the object might
need. A constructor has the same name as the class that it constructs
and is similar to a method, including being able to accept arguments.
If you don't declare a constructor in your class, the compiler creates
one for you that takes no arguments and does nothing. When we say
"
newPoint()
" we're asking that a
Point
object be allocated and because
we passed in no arguments, the no-argument constructor be invoked to
initialize it.
1.7.2. Static or Class Fields
Per-object fields are usually what you need. You usually want a field in
one object to be distinct from the field of the same name in every other
object instantiated from that class.
Sometimes, though, you want fields that are shared among all objects
of that class. These shared variables are known as
class variables
vari-
ables specific to the class as opposed to objects of the class.
Why would you want to use class variables? Consider, for example, the
Sony Walkman factory. Each Walkman has a unique serial number. In
object terms, each Walkman object has its own unique serial number
field. However, the factory needs to keep a record of the next serial
number to be assigned. You don't want to keep that number with every
Walkman object. You'd keep only one copy of that number in the fact-
ory, or, in object terms, as a class variable.
You obtain class-specific fields by declaring them
static
, and they are
therefore commonly called
static fields.
For example, a
Point
object to