Topic 3.8 — Scope and Access
Goal: explain variable scope (where a variable can be used) and access control (what code can access fields/methods),
including the roles of private and public.
The big idea
Scope is about where a variable exists and can be used (local vs instance vs class).
Access is about who is allowed to use a class’s fields/methods (private vs public).
Scope levels (fast)
| Kind | Where declared | Where usable |
|---|---|---|
| Local | inside a method / block | only inside that block |
| Instance | inside a class (not static) | in instance methods (for that object) |
| Class | inside a class with static |
in static methods (class-wide) |
Local scope example
Variables declared inside an if or loop only exist inside that block.
public void demo(int x) {
if (x > 0) {
int y = x * 2; // y exists only inside this if-block
// System.out.println(y); // ✅ here
}
// System.out.println(y); // ❌ y not in scope here
}
Instance variables: scope across methods
Instance variables are declared in the class and can be used by instance methods.
public class Counter {
private int value; // instance variable
public void inc() { value++; }
public int get() { return value; }
}
Every Counter object has its own value.
Shadowing (name collision)
If a local variable has the same name as an instance variable, the local one “wins” inside that scope.
private int score;
public void setScore(int score) {
score = score; // ❌ sets parameter to itself
}
You’ll fix this with this.score = score; in Topic 3.9.
Access control: private vs public
| Modifier | Who can access? | Typical use |
|---|---|---|
private |
only inside the same class | fields (protect state) |
public |
any code can access | methods (the “interface”) |
Why make fields private?
- Prevents other code from changing data in unsafe ways.
- Forces updates to go through methods (so you can validate).
- Makes the class easier to maintain (you can change internals later).
// Better design
private int age;
public void setAge(int a) {
if (a >= 0) age = a;
}
Quick self-check
- What does “scope” mean?
- Where can a local variable be used?
- What does
privateprevent? - Why do we usually make fields
private? - What is shadowing? (Why is it confusing?)