Page 251 - Introduction to Programming with Java: A Problem Solving Approach
P. 251
variable within the for loop’s header. The scope of such a variable is the for loop’s header plus the for loop’s body.
Method parameters are usually not considered to be local variables, but they are very similar to local variables in that they are declared and used “locally” inside a method. As with local variables, the scope of a method’s parameters is limited to within the body of that method.
Let’s round out the discussion of scope by comparing local scope to the scope used by instance variables. While variables with local scope can be accessed only within one particular method, instance variables can be accessed by any instance methods within the instance variable’s class. Furthermore, if an instance vari- able is declared with the public access modifier, it can be accessed from outside of the instance variable’s class (with the help of an instantiated object from the instance variable’s class).
Mouse2Driver Class
To illustrate local variable principles, we present the Mouse2 program in Figures 6.13 and 6.14. The code includes line numbers to facilitate tracing in an end-of-chapter exercise. The main method in the Mouse2Driver class has three local variables—stdIn, mickey, and days. These appear in the UML class diagram note at the top of Figure 6.12, and they also appear as declarations in the main method in Figure 6.13.
6.9 LocalVariables 217
1 /******************************************************
2 *
3 *
4*
Apago PDF Enhancer
5
*
6
This is a driver for the Mouse2 class.
******************************************************/
7
8
import java.util.Scanner;
9
10
public class Mouse2Driver
11
{
12
public static void main(String[] args)
13
{
Mouse2Driver.java
Dean & Dean
14
Scanner stdIn = new Scanner(System.in);⎫ Mouse2 mickey = new Mouse2(); ⎬ int days; ⎭
mickey.setPercentGrowthRate(10);
System.out.print("Enter number of days to grow: ");
days = stdIn.nextInt();
mickey.grow(days);
System.out.printf("Age = %d, weight = %.3f\n",
mickey.getAge(), mickey.getWeight());
// end main
15
16
17
18
19
20
21
22
23
24
}
25
}
// end class Mouse2Driver
local variables
Figure 6.13
Mouse2Driver class that drives the Mouse2 class in Figure 6.14