Chapter 14: Encapsulation

Imagine we’re sitting together in a quiet Mumbai café — it’s evening, the rain has just stopped, and I’m going to explain encapsulation like I’m teaching my younger brother who’s just starting to understand why professional developers are so strict about it.

We’ll go super slowly, with lots of real-life analogies, complete runnable programs, step-by-step breakdowns, tables, common mistakes with fixes, and plenty of examples you can copy-paste and run right now.

Let’s dive in!

1. What is Encapsulation? (The Big Idea)

Encapsulation means wrapping data (variables) and methods (behavior) together inside a class, and controlling access to that data from outside the class.

In simple words:

  • Hide the internal details (data) from the outside world
  • Expose only what is necessary through public methods (getters and setters)

Real-life analogy: Think of a medicine capsule.

  • The medicine (data) is hidden inside
  • You only see the outer shell (public interface)
  • You can swallow (use) it, but you cannot directly open it and mess with the powder inside — that’s encapsulation!

In Java, we achieve this using access modifiers and getters/setters.

2. Access Modifiers (The Four Levels of Visibility)

Java has four access modifiers that control who can see/access a field or method.

Modifier Visibility (Who can access?) Real-life analogy
public Everyone (any class, any package) Public park — anyone can enter
protected Same package + subclasses (even in different packages) Family members + close friends
default (no keyword) Only within the same package Apartment building — only residents
private Only within the same class Your personal diary — only you can read

Quick rule of thumb for beginners:

  • Fields (variables) → almost always private
  • Methods → public if they are part of the interface, private if they are helpers

3. Data Hiding – Why Make Fields Private?

If fields are public, anyone can directly change them — leading to bugs, invalid states, and hard-to-debug code.

Bad Example (No Encapsulation):

Java

Good Example (With Encapsulation):

Java

Test it:

Java

Output:

text

4. Getters and Setters (The Standard Way)

Getter → method to read a private field Setter → method to write/update a private field (with validation)

Naming convention (very important!):

  • For field private int age;
    • Getter: public int getAge()
    • Setter: public void setAge(int age)

Complete Example: Student Class with Full Encapsulation

Java

Test it:

Java

Output:

text

5. Quick Recap Table (Your Cheat Sheet)

Concept Best Practice / Rule Example
Fields Always private private double balance;
Getters public type getFieldName() public double getBalance()
Setters public void setFieldName(type value) + validation public void setAge(int age)
public Use for methods that are part of the public API public void withdraw(double amount)
private Use for helper methods & internal fields private void updateGrade()
protected Use when subclasses need direct access (We’ll see more in inheritance)
default Use only when package-level access is enough Rarely used in modern code

6. Common Mistakes & Fixes

Mistake Problem Fix
Making fields public Anyone can set invalid values Make fields private, use setters
No validation in setters Invalid data (negative balance, age -5) Add checks in setters
Getter returns mutable object Outside code can modify internal state Return copy or immutable object
Forgetting this. in setters Parameter shadows field Use this.field = value;
No getters/setters at all Cannot access data safely Provide public getters & controlled setters

7. Homework for You (Practice to Master!)

  1. Basic: Create Employee class with private fields (id, name, salary). Add constructors, getters, setters (validate salary > 0).
  2. Medium: Create Product class (name, price, quantity). Add method applyDiscount(double percent) with validation (0–100%).
  3. Advanced: Create Person class with private birthYear. Add getter getAge() that calculates age based on current year (use java.time.Year.now().getValue()).
  4. Fun: Create Temperature class with private celsius. Add getters/setters for Celsius, Fahrenheit, Kelvin (convert automatically).
  5. Challenge: Fix this bad code:
    Java

You’re doing fantastic! Encapsulation is what makes your code safe, readable, and professional — now you’re writing real-world quality Java code.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *