Java Reference
In-Depth Information
FIGURE 2.2
The local variable greeting points to an object on the heap.
Call stack memory
for wheelClick.
Heap Memory
pi
3.14159
greeting
“The mouse ate the 3.14159”
The String object remains on the
heap and wheelClick
returns a reference to it.
pi and greeting go out of
scope when wheelClick returns.
On line 21, the
leftClick
method has one local variable:
clickCount
. The
clickCount
parameter just happens to match the identifi er of the
clickCount
fi eld. In these situations,
the local variable is seen fi rst by the method and you must use the
this
reference to
distinguish between the instance and local variable. The
clickCount
displayed on line 22 is
the value of the parameter. To assign the
clickCount
parameter to the
clickCount
fi eld, we
must use
this.clickCount
on line 23 to refer to the fi eld.
Examine the following statements and try to determine the output:
4. Mouse m = new Mouse();
5. m.clickCount = 2;
6. System.out.println(m.wheelClick());
7. m.leftClick(1);
8. System.out.println(m.clickCount);
The fi eld
hasWheel
initializes to
false
, so calling
wheelClick
on line 6 causes
“No
wheel found”
to be returned. Calling
leftClick
with
1
as the argument causes the
1
to be
displayed and also assigned to the fi eld
clickCount
. Therefore, the output is
No wheel found
Left click 1 times
1
Declaring Arrays
The exam objectives state that you should be able to “develop code that declares, initializes,
and uses arrays.” An
array
is a contiguous chunk of memory on the heap representing
a fi xed-size collection of values that all have the same data type. An array in Java is an
Search WWH ::
Custom Search