Page 382 - Introduction to Programming with Java: A Problem Solving Approach
P. 382
348 Chapter 9 Classes with Class Members Default Values
Class variables use the same default values as instance variables:
Class Variable's Type
Default Value
integer
0
floating point
0.0
boolean
false
reference
null
It follows that the default values for Figure 9.1’s class variables are:
mouseCount = 0
youngestMouse = null
averageLifeSpan = 0.0
simulationDuration = 0
researcher = null
noiseOn = false
Presumably, the program updates mouseCount, youngestMouse, and averageLifeSpan as it runs.
The default values of averageLifeSpan and simulationDuration are zero like mouseCount,
but in Figure 9.1 the defaults don’t apply because the declarations include initializations. Even though we ex-
Let’s now compare class variables, instance variables, and local variables in terms of their scopes. You can access a class variable from anywhere within its class. More specifically, that means you can access class variables from instance methods as well as from class methods. That contrasts with instance variables, which you can access only from instance methods. Thus, class variables have broader scope than instance variables. Local variables, on the other hand, have narrower scope than instance variables. They can be ac- cessed only within one particular method. Here is the scope continuum:
local variables instance variables class variables
narrowest scope broadest scope
Having narrower scope for local variables might seem like a bad thing because it’s less “powerful,” but it’s actually a good thing. Why? Narrower scope equates to more encapsulation, and as you learned in Chapter 6, encapsulation means you are less vulnerable to inappropriate changes. Class variables, with their broad scope and lack of encapsulation, can be accessed and updated from many different places, and that makes programs hard to understand and debug. Having broader scope is necessary at times, but in general you should try to avoid broader scope. We encourage you to prefer local variables over instance variables and instance variables over class variables.
Apago PDF Enhancer
pect the program to recompute averageLifeSpan, we initialize it to provide documentation of what we think is a reasonable value. We also initialize simulationDuration (to 730) even though we expect the program to reassign simulationDuration with a user-entered value. Presumably, the program prompts the user to enter the number of days to simulate. With appropriate code, the user might be invited to enter 1 to get a “standard” 730-day simulation.
Scope