B3.1.5 · OOP for a single class
Encapsulation & accessors
By the end you can
Apply data hiding using private fields, public getters, and validating setter guard clauses.
Imagine if anyone could walk into a bank vault, open any safe deposit box, and change the cash numbers on a ledger. Financial catastrophe would ensue immediately. In software engineering, (also known as information hiding) prevents this disaster by ensuring that an object’s internal fields cannot be manipulated directly by external code.
How encapsulation is achieved#
Encapsulation follows a simple two-step rule:
- Declare all instance variables with the
privateaccess modifier (-in UML). - Provide public to interact with the data:
- Getters (Accessors): Public methods that return the attribute value (e.g.
public double getBalance()). - Setters (Mutators): Public methods that accept a new value and validate it before updating the field.
- Getters (Accessors): Public methods that return the attribute value (e.g.
The power of setter validation guards#
Why not just make fields public? Consider setting a bank account balance:
// Without encapsulation (DANGEROUS):
account.balance = -50000; // Direct corruption! No validation possible.
// With encapsulation (PROTECTED):
public void setBalance(double amount) {
if (amount >= 0) {
this.balance = amount;
} else {
System.out.println("Error: Negative balance rejected!");
}
}By channeling all state changes through a setter, the class maintains complete control over its own invariants.
Check yourself
Encapsulation and accessors
Quick questions, made fresh every time and marked here. Do a few until they feel easy.
Exam practice
Paper 1-style questions
3 questions · 9 marks
Write your answer as you would in the exam, then show the mark points and tick each one your answer made. These are our own questions in the style of the exam, not past-paper questions.
1.Explain the concept of encapsulation and state two distinct benefits it provides in software design.
[4]Explain: Give reasons: say what happens AND why, or how one thing causes another.
2.Construct a Java mutator method (setter) for 'int age' in a Person class that enforces that age cannot be negative.
[3]Construct: Draw or write it out (a table, a diagram, a program).
3.Describe how encapsulation allows a developer to make an attribute read-only to external classes.
[2]Describe: A detailed account: say what happens, step by step if it is a process.
In a nutshell
- Encapsulation bundles data attributes and methods together while hiding internal implementation details from external code.
- Private fields prevent unauthorized outside code from directly corrupting an object’s state.
- Accessors (getters) provide controlled read access to private attributes.
- Mutators (setters) provide controlled write access, enforcing validation rules and business invariants before assigning values.
