Encapsulation in Java


1. What is Encapsulation?

Encapsulation is a mechanism of wrapping data (variables) and methods (functions) together into a single unit, typically a class, and restricting direct access to some of the object’s components. This is done to protect the internal state of the object and ensure controlled access.

Think of it as a capsule: you can see some parts, but the inner workings are hidden and safe.


2. Key Features of Encapsulation

  1. Data Hiding – Internal object details are hidden from outside classes.
  2. Controlled Access – Access to fields is controlled via getter and setter methods.
  3. Flexibility & Maintainability – Internal implementation can be changed without affecting external code.

3. How to Achieve Encapsulation in Java

Encapsulation is achieved by:

  1. Declaring class variables as private.
  2. Providing public getter and setter methods to access and update the variables.

4. Example of Encapsulation

class Person {
    // Private variables
    private String name;
    private int age;

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

    // Setter method for name
    public void setName(String name) {
        this.name = name;
    }

    // Getter method for age
    public int getAge() {
        return age;
    }

    // Setter method for age with validation
    public void setAge(int age) {
        if(age > 0) {          // only allow positive age
            this.age = age;
        } else {
            System.out.println("Age must be positive.");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Person p = new Person();

        // Set values using setter methods
        p.setName("Alice");
        p.setAge(25);

        // Get values using getter methods
        System.out.println("Name: " + p.getName());
        System.out.println("Age: " + p.getAge());
    }
}

✅ Output:

Name: Alice
Age: 25

Notice how the internal variables name and age are private and cannot be accessed directly from outside the class. Access is only through controlled getter/setter methods.


5. Benefits of Encapsulation

  1. Control over data – You can validate or restrict changes to fields.
  2. Increased security – Prevents unauthorized access.
  3. Ease of maintenance – Internal implementation can change without affecting other classes.
  4. Improves modularity – Keeps code organized and easier to understand.

6. Quick Summary Table

FeatureDescription
Access Modifierprivate for fields, public for getters/setters
PurposeProtect object state and provide controlled access
Getter MethodReturns the value of private variables
Setter MethodSets the value of private variables (can validate)

Leave a Reply