Unit 3 Cycle 1 Day 17: Encapsulation and Private Fields
Share
Encapsulation and Private Fields
Section 3.9 — Scope and Access
Key Concept
Encapsulation is the practice of hiding internal implementation details and exposing only a controlled public interface. Making instance variables private prevents external code from directly modifying an object's state. Instead, public methods provide validated access. This protects data integrity: a setBalance() method can reject negative values, but a public balance field cannot. The AP exam tests encapsulation by asking whether code that directly accesses private fields will compile, and by testing proper getter/setter patterns.
Consider the following code.
Which statement best describes a problem with this class design?
Answer: (B) Instance variables should be private to enforce encapsulation.
Public instance variables break encapsulation. Any code can modify degrees and scale directly, bypassing any validation. Making them private with getters/setters controls access.
Why Not the Others?
(A) Different parameter names are fine and avoid the shadowing problem.
(C) toString() is useful but not a design flaw. Encapsulation is the primary issue.
(D) Public instance variables are a significant design problem in OOP.
Common Mistake
Encapsulation principle: instance variables should be private, with public getter/setter methods. This allows the class to validate data and control how fields are modified.
AP Exam Tip
The AP exam expects instance variables to be private. Public fields are considered bad practice. Look for this in class design questions.