Java Reference
In-Depth Information
Java syntax: Referencing a field
expr
.
field-name
Example
:
(
new
Date()).x
Purpose
: To reference field
field-
name
of the folder whose name is
given by the value of expression
expr
.
Java syntax: Calling an instance method
expr
.
method-name
(
arguments
)
Example
: (
new
Date()).getyear()
Purpose
: To call instance method
method-name
that appears in the folder whose name is given by
the value of expression
expr
. If the method is a pro-
cedure, the call needs a semicolon.
Employee e=
new
Employee("Hall", 2000);
If evaluation of the new-expression in this assignment created the folder that is
on the right side of Fig. 3.3, the value
a0
would be stored in e.
But an
Employee
new-expression can appear in many other places —wher-
ever an expression of type
Employee
can appear. For example, the following
statement creates an Employee and prints its description using its
toString
function; thereafter, the newly created folder cannot be referenced anymore:
System.out.println(
new
Employee("Gries", 1966));
This example may not seem so useful. Here is a more useful one. We would
like to obtain the current year (or month, day, minute, etc.). We can do this by
constructing a new instance of class
Date
(in package
java.util
), calling its
function
getYear
, and adding
1900
to the result:
int
year= (
new
Date()).getYear() + 1900;
In this example, a desired value is retrieved from the new
Date
folder, and the
Date
folder is never used again.
In this text, you will come across other cases where a new-expression is used
in places other than the righthand side of an assignment. Get used to the fact that
the new-expression is just that, a new kind of expression.
a0
a0
Employee
Employee
getName()
setName(String)
getStart()
setStart(
int
)
getCompensation()
addToSalary(
double
)
toString()
Employee()
getName()
setName(String)
getStart()
setStart(
int
)
getCompensation()
addToSalary(
double
)
toString()
Employee()
null
name
name
Gries
0
1966
start
start
50000.
50000.
salary
salary
Figure 3.3:
Evaluating a new-expression
Search WWH ::
Custom Search