Java Reference
In-Depth Information
Until
x
is assigned a value, it cannot appear within an expression, and the compiler will
gladly remind you of this rule.
The following
Mouse
class is another example of using local variables. Examine the code
and see if you can distinguish the local variables from the instance variables. Does the
Mouse
class compile successfully?
1. public class Mouse {
2. public boolean hasWheel;
3. private int clickCount;
4.
5. public int rightClick(double d) {
6. int response = (int) d;
7. return response;
8. }
9.
10. public String wheelClick() {
11. if(hasWheel) {
12. double pi = 3.14159;
13. String greeting = “The mouse ate the “ + pi;
14. return greeting;
15. } else {
16. String error = “No wheel found”;
17. return error;
18. }
19. }
20.
21. public void leftClick(int clickCount) {
22. System.out.println(“Left click “ + clickCount + “ times”);
23. this.clickCount = clickCount;
24. }
25.}
Although there may be some confusion about
clickCount
in the
leftClick
method, this
class compiles fi ne. The
Mouse
class has two instance variables:
hasWheel
and
clickCount
.
The
rightClick
method has two local variables:
d
and
response
. When the
rightClick
method is invoked,
d
and
response
get allocated in memory. When
response
is returned on
line 7, a copy of
response
is sent to the calling method and both
d
and
response
go out of scope.
The
wheelClick
method has three local variables:
pi
,
greeting
, and
error
. If
hasWheel
is true, this method returns
greeting
, at which point
pi
and
greeting
go out of scope.
The
String
object
“The mouse ate the 3.14159”
is on the heap, as shown in Figure 2.2,
so it is not destroyed when the method returns. The same scenario happens when
error
is
returned:
error
goes out of scope but the
String
“No wheel found”
is on the heap and still
exists (for as long as it is reachable by a reference).
Search WWH ::
Custom Search