Java Reference
In-Depth Information
creates a new object of the specified class and associates it with the class variable.
1
Because the class variable now names an object of the class, we will often refer to the
class variable as an object of the class. (This is really the same usage as when we refer to
an
int
variable
n
as “the integer
n
,” even though the integer is, strictly speaking, not
n
but the value of
n
.)
Unlike what we did in Display 4.1, the declaration of a class variable and the
creation of the object are more typically combined into one statement, as follows:
DateFirstTry date1 =
new
DateFirstTry();
The
new
Operator
The
new
operator is used to create an object of a class and associate the object with a
variable that names it.
SYNTAX
Class_Variable
=
new
Class_Name
( );
EXAMPLE
DateFirstTry date;
date =
new
DateFirstTry();
which is usually written in the following equivalent form:
DateFirstTry date =
new
DateFirstTry();
Instance Variables and Methods
We will illustrate the details about instance variables using the class and program
in Display 4.1. Each object of the class
DateFirstTry
has three instance variables,
which can be named by giving the object name followed by a dot and the name of the
instance variable. For example, the object
date1
in the program
DateFirstTryDemo
has the following three instance variables:
date1.month
date1.day
date1.year
Similarly, if you replace
date1
with
date2
, you obtain the three instance variables
for the object
date2
. Note that
date1
and
date2
together have a total of six instance
variables. The instance variables
date1.month
and
date2.month
, for example, are two
different (instance) variables.
1
For many, the word “new” suggests a memory allocation. As we will see, the
new
operator does
indeed produce a memory allocation.