What is Encapsulation?

Encapsulation is the process of wrapping data (variables) and code (methods) together as a single unit. In simple terms, it is Data Hiding.

In university exams, a common analogy is a Medical Capsule. Just as the capsule protects the medicine inside from the outside environment, Encapsulation protects the data inside a class from unauthorized access by other classes.


How to Achieve Encapsulation?

To implement Encapsulation in Java, you follow two main steps:

  1. Declare variables as private: This ensures the variables cannot be accessed directly from outside the class.

  2. Provide public Getter and Setter methods: These methods allow other classes to view or modify the variables in a controlled way.


Breakdown of Your Code

Let’s look at your Student class example:

Java

 
class Student {
    // 1. Private variable - Hidden from the outside world
    private int age;

    // 2. Setter Method - To update the age safely
    public void setAge(int a) {
        if (a > 0) { // Encapsulation allows us to add validation logic!
            age = a;
        } else {
            System.out.println("Error: Age cannot be negative.");
        }
    }

    // 3. Getter Method - To read the age safely
    public int getAge() {
        return age;
    }
}

Why is Encapsulation Important for Students?

A. Security & Control

Without encapsulation, anyone could set a student’s age to -500 or 9999. With a Setter method, you can add an if statement to check if the data is valid before saving it.

B. Data Hiding

The “outside world” (other classes) doesn’t need to know how the data is stored. They only need to know how to use the public methods. This makes your code more modular and easier to maintain.

C. Flexibility

If you decide to change the variable age from an int to a short later, you only have to change the code inside the class. No other part of the program will break because they are only interacting with your public methods.


Using Encapsulated Classes in Main

Java

 
public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();
        
        // s1.age = 20;  <-- This would cause a COMPILE ERROR because age is private.
        
        s1.setAge(20); // Correct way to set data
        System.out.println("Student Age: " + s1.getAge()); // Correct way to get data
    }
}

Summary Table for Revision

ComponentVisibilityPurpose
VariablesprivateTo hide sensitive data.
GetterspublicTo provide read-only access to data.
SetterspublicTo provide write access with validation.