5.5

advertisement
Homework 5.3
♫ What are the lifetimes of an instance variable, a local variable, and a parameter?
♪ Instance variable – last for the lifetime of an object.
♪ Local variable – single execution of a method.
♪ Parameter – formal parameters last for a single execution of a method.
♫ What is shadowing? Give an example and describe the bad things that shadowing
might cause to happen in a program.
♪ Shadowing is used to distinguish between a local and a global variable with the
same name. iAmAVariable is local variable but this.iAmAVariable is a global
variable. If the wrong variable is used in the program it will cause a run-time error
or a logic error. If it is a logic error the programmer might not catch it.
♫ Consider the following the code segment:
public class SomeClass{
private int a, b;
public void aMutator(int x, y){
int c, d;
<lots of code goes here>
}
}
a. List the instance variables, parameters, and local variables in this code.
b. Describe the scope of each variable or parameter.
c. Describe the lifetime of each variable or parameter.
♪ a. instance variable – SomeClass, parameter – int x, y , local variable – a, b.
♪ b. int x, y – clientMethod, SomeClass – helperMethod, a, b - helperMethod
and clientMethod
♪ c. SomeClass – lifetime of the object, int x, y – single execution, a, b – single
execution.
Download