AP® Computer Science A · Unit 3 · Topic 3.3
private Fields and Encapsulation
private locks a field so only code inside its own class can touch it directly; outside code must go through public methods, which can check a value before it's stored.
You wrote the class, so you decide what counts as a valid value for its fields. Mark a field private and the compiler enforces that decision: only code inside that same class can read or write the field directly. Any outside code that tries gets a compile-time error, not a runtime surprise. This is encapsulation — bundling data with the code that's allowed to touch it, so the object controls its own state instead of trusting every piece of code that uses it.
Accessors (getters) and mutators (setters) are the public doorway you build into that locked room. A getter like getBalance() just hands back a copy of the value. A setter like setBalance(double amount) can check the value first — reject a negative balance, clamp a number to a range, log a change — before it ever gets stored in the field. That check is the whole point: it's a checkpoint that a bare public field can never have, because public code can assign anything with no one standing guard.
This sets up constructors and methods, which are the other public doorways into an object: a constructor sets the initial state once when the object is built, and methods like deposit or withdraw are mutators with a purpose, changing balance only in ways the class considers legal. Private fields are the reason those methods matter — without the lock, there's nothing for them to protect.
Key terms
- private
- An access modifier restricting a field or method so only code inside the same class can use it directly.
- encapsulation
- Bundling data with the methods that control access to it, hiding the data's direct implementation from outside code.
- accessor (getter)
- A public method that returns the value of a private field without allowing direct outside access.
- mutator (setter)
- A public method that changes a private field's value, often after validating or adjusting the new value first.
Watch it explained
- How it worksHow does private stop outside code from reaching an instance variable directly?
- Worked exampleTrace what happens when outside code tries to set a private balance field on its own.
- How it worksHow does an accessor and mutator pair put a checkpoint in front of the data?
- Common mistakeWhy isn't making everything public simpler and therefore better?
Check yourself
End of topic.