Unit 3 Cycle 1 Day 9: Scope and Access Control
Share
Scope and Access Control
Section 3.9 — Scope and Access
Key Concept
Access control in Java uses modifiers to restrict visibility. private members are accessible only within the class where they are declared. public members are accessible from any class. There is no explicit modifier for package-private or protected access on the AP exam, but understanding private and public is essential. Encapsulation requires making instance variables private and providing public accessor and mutator methods. The AP exam tests whether code correctly accesses or is prevented from accessing private members.
Consider the following code.
What is the scope of the variable pi?
Answer: (B) It is accessible only inside the area() method.
pi is a local variable declared inside the area() method. Its scope is limited to that method. It does not exist outside of area().
Why Not the Others?
(A) pi is local, not an instance variable. Instance variables are class-wide.
(C) Even public instance variables are not accessible from any class. But pi is local, with the narrowest scope.
(D) Local variables are scoped to the method where they are declared. The constructor cannot see pi.
Common Mistake
Local variables (declared inside methods) exist only within that method. Instance variables (declared in the class but outside methods) exist for the life of the object.
AP Exam Tip
Three scope levels: (1) Local - inside a method/block. (2) Instance - inside the class. (3) Class/static - shared across all objects. AP exam tests all three.