This exercise reviews the "scope" of variables and parameters. The scope of a variable or formal parameter is the section of code that can "see" (can use) the parameter.
The scope of an instance variable includes each method body (list of statements) and each constructor body.
1. In the following program skeleton, click on each button
where it would be correct to have the statement:
In other words, click on each button where
the variable target
is in scope.
"Outsiders" can access instance variables of an object using "dot notation" unless the instance variable is private (or has default access and is in a different package...but ignore this for now.)
2. In the following program skeleton, click on each button
where it would be OK to have the statement:
3. In the following program skeleton, click on each button
where it would be OK to have the statement
Formal parameters can only be seen by the body of their own method.
4. Click on each button
where it would be OK to have the statement
It is OK for formal parameters in two different methods to use the same identifier.
5. In the following program skeleton, click on each button
where it would be OK to have the statement
sum = data ;
A local variable can only be seen in the body of its method by statements following its declaration. It is OK for local variables in different methods to use the same name.
6. Click on each button
where it would be OK to have the statement
value = 5;
If a local variable has the same name as an instance variable the local variable will be the one seen by the statements in its method that follow its declaration. (Although it is correct syntax to have both local and instance variables use the same name, it is probably a bad idea since it confuses humans.)
7. Decide if each statements sets the instance variable sum or the local variable sum.
If a local variable has the same name as an instance variable and you want to specify the instance variable, use this.
8. In the following program skeleton, decide if each statements sets the instance variable sum or the local variable sum.
If a paramenter has the same name as an instance variable and you want to specify the instance variable, use this. This is often done with constructors, where it is probably less confusing to use the same name for both.
9. Decide if each statements sets the instance variable sum or the parameter sum.
An "outsider" can change a private instance variable of an object by using an access method of the object (if there is one.)
10. In the following program skeleton, click on those buttons next to statements that change sum.