Java Reference
In-Depth Information
Java syntax: New-expression
new
class-name
(
arguments
)
Purpose
. Create a folder (instance, object).
Evaluation
. Create a folder of class
class-name
, exe-
cute the constructor call
class-name
(
arguments
), and
yield the name of the new folder as the value.
The values of type
Employee
are the names of folders of class
Employee
.
When a variable of type
Employee
is first declared, it contains the value
null
, which means that it does not contain the name of a folder.
3.2.2
The new-expression
The new-expression is used to create new folders, or instances, of a class.
Consider this expression, where class
Employee
is given in Fig. 3.1:
Activities
3-4.1, 3-5.2
new
Employee("Gries", 1966)
Its evaluation is done in three steps:
1. Create a new folder of class
Employee
and place it in
Employee
's file
drawer. Its fields are initialized according to the declarations of the fields.
The first part of the new-expression, “
new
Employee
” tells us to do this.
2. Execute the constructor call
Employee("Gries", 1966);
where the con-
structor
Employee
that is called is the one in the newly created folder
whose parameter types match the argument types of the call.
3. Yield as the value of the call the name of the new folder.
We evaluate the new-expression
new
Employee("Gries", 1966)
. Step 1 is
to create a new folder of class Employee; the folder is shown in the left of Fig.
3.3. The fields have initial values as given by their declarations in the class —
default values are used if an initializing declaration is not used.
Step 2 is to execute the constructor call
Employee("Gries", 1966)
. We do
this here by stepping over the call. According to the specification of the con-
structor, the first argument is stored in field
name
and the second in field
start
.
We show the result on the right side of Fig. 3.3.
Step 3 is to yield the name
a0
as the result of the expression evaluation.
Here is some terminology. The manilla folder created by evaluating a new-
expression is called an
instance
of the class, or an
object
of the class. Evaluating
a new-expression
instantiates
the class by creating an instance of it.
Placement of a new-expression
The main use of the new-expression is on the righthand side of an assign-
ment statement, for example, as in:
Search WWH ::
Custom Search