Unit 3 Cycle 2 Day 18: Scope Error: Local vs Instance
Share
Scope Error: Local vs Instance
Section 3.9 — Scope and Access
Key Concept
A scope error with local versus instance variables occurs when a method declares a local variable with the same name as an instance variable. Inside that method, the local variable shadows the field. Assigning to the local variable does not change the instance variable. This is a common bug: void setX(int val) { int x = val; } creates a new local x instead of assigning to this.x. The AP exam presents subtle versions of this error where the shadowing is not immediately obvious.
Consider the following class.
After executing Timer t = new Timer(10); t.tick(); System.out.println(t.getSeconds());, what is printed?
Answer: (B) 10
The tick() method declares a LOCAL variable seconds that shadows the instance variable. The local variable gets 9, but the instance variable is unchanged. getSeconds() returns the instance variable: 10.
Why Not the Others?
(A) The instance variable is never modified. The local variable shadows it.
(C) The instance variable retains its original value of 10.
(D) The code compiles. Local variables can have the same name as instance variables (shadowing).
Common Mistake
Declaring a local variable with the same name as an instance variable creates shadowing. The local variable hides the field. To modify the field, use this.seconds or do not redeclare.
AP Exam Tip
Variable shadowing is a common AP exam trap. If a local variable and instance variable share a name, the local takes precedence without this.