Java Encapsulation

Encapsulation is one of the fundamental principles of object-oriented programming (OOP) in Java. It refers to the bundling of data (attributes) and methods that operate on the data into a single unit, usually a class. Encapsulation restricts direct access to some of an object's components, which can prevent the accidental modification of data.

1. Benefits of Encapsulation

  • Improves maintainability and flexibility of code.
  • Enhances data security by controlling access.
  • Promotes modular design.

2. Implementing Encapsulation

Encapsulation in Java is achieved using access modifiers to restrict access to class members. Typically, you make class attributes private and provide public getter and setter methods to access and modify them.

3. Example

public class Employee {
    // Private attributes
    private String name;
    private int age;

    // Public getter and setter methods
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age > 0) {
            this.age = age;
        } else {
            System.out.println("Please enter a valid age.");
        }
    }
}

4. Accessing Private Members

Since the attributes are private, they cannot be accessed directly from outside the class. You must use the public getter and setter methods.

public class Main {
    public static void main(String[] args) {
        Employee emp = new Employee();
        emp.setName("John Doe");
        emp.setAge(30);
        System.out.println("Name: " + emp.getName());
        System.out.println("Age: " + emp.getAge());
    }
}

5. Key Takeaways

  • Encapsulation bundles data and methods within a class.
  • Use access modifiers to control access to class members.
  • Getter and setter methods provide controlled access to private attributes.
  • Encapsulation enhances code maintainability and security.