Page 245 - Introduction to Programming with Java: A Problem Solving Approach
P. 245

                Figure 6.8
MouseDriver2 class that drives Mouse class in Figure 6.9
We’ll discuss local variables in detail later, but for now, just realize that growthRate (abbreviated to rate in the trace setup), gus, and jaq are considered to be local variables because they’re declared and used “locally” within one particular method, the main method. That’s different from the age, weight, and percentGrowthRate instance variables, which are declared outside of all methods, at the top of the class. Note that stdIn is another local variable within main, but there’s no need to trace it because it’s in- stantiated from an API class, Scanner. There’s no need to trace API classes because they’ve already been traced and tested thoroughly by the good folks at Sun. You can assume that they work properly.
Now let’s examine the trace setup’s parameters. The setPercentGrowthRate method has two parameters—percentGrowthRate, abbreviated to rate in the trace setup, and the this reference, an implicit parameter. As you may recall, the this reference points to the calling object. For the
6.7 TracinganOOPProgram 211
 9
10
public class MouseDriver2
11
{
12
public static void main(String[] args)
13
{
14
Scanner stdIn = new Scanner(System.in);
double growthRate;
Mouse gus, jaq;
System.out.print("Enter % growth rate: ");
growthRate = stdIn.nextDouble(); ⎫ gus = new Mouse(); ⎬ gus.setPercentGrowthRate(growthRate); ⎭ gus.grow();
1 /*****************************************************
2 *
3 *
4*
5
MouseDriver2.java
Dean & Dean
This is a driver for the Mouse class.
*****************************************************/
6
7
8
import java.util.Scanner;
*
  15
  16
17
  18
 19
20
 21
22
23
gus.display();
neAwpMaougseo(); PDF E jaq.grow();
jaq.display();
// end main
 24
jaq =
  25
26
27
}
28
}
// end class MouseDriver2
Sample session:
Enter % growth rate: 10
Age = 1, weight = 1.100
Age = 1, weight = 1.000
jaqdoesn’tgrow.Abug!
This declares reference variables but does not initialize them.
 nhancer
Try to group initialization activities.
 There’s a logic error here. We “accidentally” forget to initialize the growth rate in jaq.
     

































   243   244   245   246   247