Encapsulation with Getters/Setters
- coding z2m
- Jun 30
- 3 min read
Updated: Jul 2
🎯 Goal of Encapsulation
Encapsulation is the practice of hiding internal object state and exposing access via controlled methods (getters/setters).It enforces data integrity and separates concerns.
🔒 What is Encapsulation?
Encapsulation is the principle of bundling data (attributes) and methods (functions) that operate on the data into a single unit, typically a class. It restricts direct access to some of the object's components, which is commonly done using access modifiers like private, protected, and public.
🎯 How It Separates Concerns
Internal vs. External Logic
Internal concern: How something is done (e.g., how data is stored or manipulated).
External concern: What can be done with it (e.g., public methods you can call).
By encapsulating internal logic, users only deal with the interface, not how it works.
✅ Example: You can call account.deposit(100) without needing to know how the account tracks balance.
Reduces Interdependency
When details are hidden, other parts of the program don’t rely on internal workings, reducing coupling.
This makes code easier to change, test, and debug independently.
Improves Maintainability
If the internal logic changes, the interface can remain the same.
You can fix bugs or improve performance without affecting external code.
Supports Modular Design
Each class handles only its specific concern, encapsulating its logic.
Encourages single responsibility principle—a key aspect of separation of concerns.
🧠 Real-World Analogy
Think of a TV remote:
You press a button to change the channel.
You don’t need to know how infrared signals or circuitry work.
The remote encapsulates the internal complexity and separates your concern (switching channels) from the technical implementation.
🏥 Real-World Example: Patient Medical Record System
Think of a hospital system where you track patient records.You want to:
Protect private data like age, diagnosis
Allow controlled access to read/update info
Add logic like validation or logging inside setters
🔹 Java Code Example: PatientRecord public class PatientRecord {
// 🔐 Fields are private (Encapsulation)
private String name;
private int age;
private String diagnosis;
// ✅ Constructor
public PatientRecord(String name, int age, String diagnosis) {
this.setName(name); // using setter ensures validation
this.setAge(age);
this.setDiagnosis(diagnosis);
}
// ✅ Getter for name
public String getName() {
return name;
}
// ✅ Setter for name
public void setName(String name) {
if (name != null && !name.trim().isEmpty()) {
this.name = name;
} else {
System.out.println("Invalid name input");
}
}
// ✅ Getter for age
public int getAge() {
return age;
}
// ✅ Setter for age with validation
public void setAge(int age) {
if (age > 0 && age < 130) {
this.age = age;
} else {
System.out.println("Invalid age: " + age);
}
}
// ✅ Getter for diagnosis
public String getDiagnosis() {
return diagnosis;
}
// ✅ Setter for diagnosis
public void setDiagnosis(String diagnosis) {
this.diagnosis = diagnosis;
}
// 🖨️ Display method
public void displayRecord() {
System.out.println("Patient: " + name);
System.out.println("Age: " + age);
System.out.println("Diagnosis: " + diagnosis);
System.out.println("------------------------------");
}
} 🔹 Usage in main() public class Main {
public static void main(String[] args) {
PatientRecord p1 = new PatientRecord("Alice", 28, "Flu");
PatientRecord p2 = new PatientRecord("Bob", -3, ""); // triggers validation
p1.displayRecord();
p2.displayRecord();
// Update diagnosis using setter
p1.setDiagnosis("Recovered from Flu");
p1.displayRecord();
}
}
🧠 Why Is This a Good Encapsulation Example?
Feature | Purpose |
private fields | Data hiding (no direct access from outside) |
get/set methods | Controlled access with validation logic |
Logic in setters | Protects against bad input (negative age, null name) |
Centralized validation | Ensures data correctness wherever values are set |
💬 Interview-Ready Explanation
"I used encapsulation in the PatientRecord class by declaring fields private and exposing public getters and setters. This allowed me to protect sensitive medical data and enforce validation rules (like age not being negative). It's a real-world reflection of protecting access to critical records in a hospital system."
🚫 Without Encapsulation (❌ Bad Practice) public class PatientRecord {
public String name;
public int age;
public String diagnosis;
// Anyone can do p.age = -90; --> No protection at all!
} 💡 Bonus Design Thoughts
In enterprise-grade code, use Java Records (Java 21) or Lombok annotations if validation is not needed.
You could log every setter call for auditing changes to sensitive data.
Combine with access levels: some fields only have getters (e.g., getPatientId() with no setter). 🧪 Student Challenge Task
Create a class BankAccount with:
accountHolder, accountNumber, balance
getBalance() should return balance
setBalance(double) should reject negative balance
withdraw(double) method that only withdraws if balance is sufficient
Comments