🔐 Encapsulation in Java – Explained Simply

Encapsulation is one of the four core Object-Oriented Programming (OOP) principles in Java. It means wrapping data (variables) and code (methods) together as a single unit — and restricting direct access to some of the object’s components.


🧠 Key Idea:

Encapsulation = Data Hiding + Controlled Access


✅ Why Use Encapsulation?

Benefit Description
🛡️ Security Prevent unauthorized access to sensitive data
🧩 Maintainability Internal code changes won’t affect external code
🎯 Control Only allow access through specific methods
🔄 Reusability Code becomes more modular and reusable

👨💻 How to Achieve Encapsulation in Java

  1. Declare class variables as private
  2. Provide public get and set methods to access and update them

📦 Example: Encapsulation in Action

public class Student {
    private String name;     // private = hidden from outside
    private int age;

    // Getter method
    public String getName() {
        return name;
    }

    // Setter method
    public void setName(String newName) {
        name = newName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int newAge) {
        if (newAge > 0) {
            age = newAge;
        }
    }
}

 

🔎 Usage:

public class Main {
    public static void main(String[] args) {
        Student s = new Student();
        s.setName("Aftab");
        s.setAge(22);

        System.out.println(s.getName());  // Output: Aftab
        System.out.println(s.getAge());   // Output: 22
    }
}

 

🚧 Without Encapsulation (Bad Practice):

public class Student {
    public String name;
    public int age;
}

➡ Anyone can set age = -100, and no one can prevent it!


📌 Summary

Concept Description
Encapsulation Binding data and behavior in a single unit
Access Modifier Use private to hide variables
Getters/Setters Use public methods to access/update variables
Main Goal Data protection, abstraction, clean code design
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.