Lesson 3.8: Scope and Access
Lesson 3.8: Scope and Access
What You'll Learn
- Define scope and identify what is accessible at any point in a class
- Distinguish local, instance, and class variable scopes
- Explain variable shadowing and use
thisto resolve it - Identify scope-related compile errors on for loop variables and redeclarations
Key Vocabulary
| Term | Definition |
|---|---|
| scope | The region of code in which a variable is accessible |
| local variable | Declared inside a method or block; only accessible within that method/block |
| instance variable | Declared in class body outside any method; accessible throughout the class |
| class variable | Declared with static in class body; accessible to all instances and static methods |
| block | Code enclosed in { }; variables declared inside are local to that block |
| variable shadowing | A local variable with the same name as an instance variable; the local variable takes precedence inside the block |
| lifetime | How long a variable exists in memory: local = method call; instance = object's lifetime |
CED EK 3.8 — Scope and Access
Scope determines where a variable can be used. A local variable's scope is the block in which it is declared. An instance variable's scope is the entire class. A class variable (static) is also accessible throughout the class. When a local variable has the same name as an instance variable, the local variable shadows the instance variable within that block.
Levels of Scope
Three Levels in One Class
public class Account {
private double balance; // instance scope: whole class
private static int count = 0; // class scope: whole class
public void deposit(double amount) {
double fee = 1.50; // local scope: this method only
balance += amount - fee;
}
public double getBalance() {
// fee is NOT accessible here -- out of scope
return balance;
}
}
Variable Shadowing
Shadowing Bug
public class Player {
private int score;
public void addPoints(int score) { // shadows instance var!
score += 10; // modifies parameter, NOT instance var
// to fix: this.score += 10; or this.score = score + 10;
}
}
When parameter score shadows instance variable score, plain score inside the method refers to the parameter. Use this.score to explicitly reference the instance variable.
Block Scope in for Loops
Loop Variable Is Local
public void printSums(int n) {
int total = 0;
for (int i = 1; i <= n; i++) {
total += i; // total is accessible: declared in same method
// i is accessible here
}
// i is NOT accessible here -- declared in for loop header
System.out.println(total);
}
AP Trap: Local Variable Declared in Loop Not Accessible After Loop
for (int k = 0; k < 5; k++) { /* k accessible here */ }
// k NOT accessible here -- compile error
Variables declared in the for loop header are scoped to the loop body.
AP Trap: Declaring Same Variable Twice in Same Scope
public void method() {
int x = 5;
int x = 10; // COMPILE ERROR: x already declared
}
You cannot redeclare a variable in the same scope. In nested blocks, you can shadow outer variables.
AP Trap: this.varName Required When Name Is Shadowed
public Dog(String name) {
name = name; // BUG: parameter shadows instance var
this.name = name; // CORRECT
}
This is the same constructor bug from 3.4 -- explained here from the scope perspective.
Real-World Connection: Think of scope like employee security badges. A local variable is a day pass (only works today). An instance variable is a permanent badge (works as long as the employee object exists).
Summary
- Local variables are declared inside a method/block and are only accessible within that block.
- Instance variables are accessible throughout the class in which they are declared.
- When a local variable and instance variable share a name, the local variable shadows the instance variable.
- Use
this.varNameto explicitly access the instance variable when shadowing occurs. - Variables declared in a for loop header are scoped to the loop body.
Practice Questions
public class Engine {
private int rpm;
public void rev(int boost) {
int extra = boost * 2;
// <-- here
}
}
public void printLast(int n) {
for (int i = 0; i < n; i++) { int sq = i*i; }
System.out.println(i);
}
i is out of scope after the loop
public void award(int score) { score += 50; }, score refers to...public void setAge(int age) { age = this.age; }
public void setAge(int age) { age = age; }
public void setAge(int age) { this.age = age; }
public void setAge(int age) { super.age = age; }
int total = 0;
for (int j = 1; j <= 4; j++) { int step = j*2; total += step; }
public void compute(int val) {
int result = val * 2;
int result = val + 10;
}
public void addCookies(int cookies) {
cookies = cookies + 10;
}where cookies is also a private instance variable.cookies = cookies + 10 modifies the parameter; this.cookies unchanged
this.cookies = cookies + 10;
Mastery: Scope and Access
acct.update(20.0) where update does balance = balance + 50.0; and balance is also a private instance variable starting at 100.0, what is the instance variable's value?II. Instance variable accessible by any method in its class
III.
this.x refers to instance variable even when parameter x shadows itWhich are TRUE?
cash AND declares double cash = 50.0; locally. Result?Get in Touch
Whether you're a student, parent, or teacher — I'd love to hear from you.
Just want free AP CS resources?
Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
Prefer email? Reach me directly at [email protected]