Encapsulation in Java | OOP Concepts

Encapsulation in Java is one of the fundamental principles of Object-Oriented Programming (OOP). It involves wrapping the data (variables) and the code (methods) together into a single unit or class, restricting direct access to some of an object’s components and protecting the internal state of the object.

Key Points on Encapsulation:

Example of Encapsulation in Java:

This example demonstrates encapsulation by using private variables with public getter and setter methods.

Code Example


public class Student {
    // Private fields - data is encapsulated
    private String name;
    private int age;

    // Constructor
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

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

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

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

    // Public setter method for age
    public void setAge(int age) {
        if (age > 0) { // Adding a check for valid data
            this.age = age;
        }
    }
}

Usage Example:

Here’s how encapsulated data can be accessed and modified using getter and setter methods.

Code Example 2


public class Main {
  public static void main(String[] args) {
    // Creating a Student object
    Student student = new Student("Alice", 20);

    // Accessing encapsulated data
    System.out.println("Name: " + student.getName());
    System.out.println("Age: " + student.getAge());

    // Modifying encapsulated data
    student.setName("Bob");
    student.setAge(25);

    // Displaying updated data
    System.out.println("Updated Name: " + student.getName());
    System.out.println("Updated Age: " + student.getAge());
    }
}

Output

Name: Alice
Age: 20
Updated Name: Bob
Updated Age: 25

Detailed Explanation:

Encapsulation is fundamental in Java and object-oriented programming, making code modular, secure, and easy to maintain.