Java Reference
In-Depth Information
ToyClass temp =
new
ToyClass("JOE", 42);
if
(variable1.equals(temp))
System.out.println("Equal");
else
System.out.println("Not equal");
In the second version, the object is created, and its reference is placed in the variable
temp
. Then
temp
is plugged in for the parameter in the
equals
method. But all the
parameter passing mechanism does is to take the reference stored in
temp
and plug it
into the parameter for
equals
. The first version simplifies the process. It creates the
reference to the object and directly plugs it into the parameter in
equals
. It bypasses the
variable
temp
but ends up plugging in the same reference as the argument to
equals
.
An expression such as
new
ToyClass("JOE", 42)
when not assigned to a variable is known as an
anonymous object
. It evaluates a refer-
ence to an object of the class. It is called
anonymous
because the object is not assigned
a variable to serve as its name. We will eventually encounter situations where the use of
such anonymous objects is common.
anonymous
object
Anonymous Objects
An expression with a
new
operator and a constructor creates a new object and returns a
reference to the object. If this reference is not assigned to a variable, but instead the
expression with
new
and the constructor is used as an argument to some method, then
the object produced is called an
anonymous object
.
EXAMPLE
if
(variable1.equals(
new
ToyClass("JOE", 42)))
System.out.println("Equal");
else
System.out.println("Not equal");
The expression
new
ToyClass("JOE", 42)
(or more exactly, the object it creates) is an
example of an anonymous object.
EXAMPLE:
Another Approach to Keyboard Input
★
This example uses the class
StringTokenizer
, which was covered in a starred section of
Chapter 4. If you have not yet covered the
StringTokenizer
class, you may omit this
example until you have covered the
StringTokenizer
class.
The program in Display 5.18 is an example of the use of both the
StringTokenizer
class and the method
Double.parseDouble
to read multiple values of type
double
entered on a single line and separated with something other than whitespace.
(continued)