AP Computer Science A · Unit 3: Class Creation
3.8 Scope and Access
Instance vs. Local Variables
Instance variables are declared inside a class but outside any method; they exist for the life of the object and are accessible to all methods in the class. Local variables are declared inside a method or constructor and only exist while that method runs — they have local scope and must be initialized before use, unlike instance variables which get default values.
Access Modifiers
private members can only be accessed within the same class, enforcing encapsulation. public members can be accessed from any class. Best practice: make instance variables private and provide public accessor (getter) and mutator (setter) methods to control how outside code reads/changes them.
Shadowing and 'this'
When a local variable (like a parameter) has the same name as an instance variable, the local variable shadows it within that method's scope — the keyword itself refers to the local one. To explicitly reference the instance variable, use this.variableName, which distinguishes the object's field from the local/parameter variable.
Key terms
- Instance variable
- A variable declared inside a class but outside any method; exists for the life of the object.
- Local variable
- A variable declared inside a method/constructor; exists only during that method's execution.
- private
- Access modifier restricting a member's access to only within its own class.
- this keyword
- Refers to the current object; used to distinguish instance variables from shadowing local variables/parameters.
- Shadowing
- When a local variable or parameter has the same name as an instance variable, hiding it within that scope.
Try an AP-style question
Code
public void m() {
for (int i = 0; i < 3; i++) { }
System.out.print(i);
}Why won't this compile?
- The loop is empty
- i must be a double
- print needs a String
- i is out of scope after the loop
Show the answer
D. Loop variable scope.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 3.8 free in APrep