Java Encapsulation

Java encapsulation is a fundamental principle of object-oriented programming (OOP) that allows for the bundling of data and methods within a single unit known as a class. It provides the means to protect data from direct access by other classes and enforces the use of accessor and mutator methods to manipulate the data. Encapsulation promotes data hiding, abstraction, and modular programming, resulting in more maintainable and secure code.

In Java, encapsulation is achieved by declaring the instance variables of a class as private, preventing direct access from outside the class. These variables can then be accessed and modified only through public methods, also known as getters and setters or accessor and mutator methods. By encapsulating data, we can control the state and behavior of an object, ensuring that it remains consistent and valid throughout its lifecycle.

Example

Here’s an example to illustrate the concept of encapsulation in Java:

public class Employee {
    private String name;
    private int age;
    private double salary;

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

    public int getAge() {
        return age;
    }

    public double getSalary() {
        return salary;
    }

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

    public void setAge(int age) {
        this.age = age;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
}

In the above example, we have a class called Employee with private instance variables name, age, and salary. These variables cannot be accessed directly from outside the class. To access or modify these variables, we provide public getter and setter methods.

The getter methods (getName(), getAge(), and getSalary()) allow other classes to retrieve the values of the private variables. On the other hand, the setter methods (setName(), setAge(), and setSalary()) enable other classes to modify the private variables, ensuring that the values are set according to certain rules or constraints defined within these methods.

Encapsulation allows us to control access to the internal state of an object, maintaining data integrity and providing a clear interface for interacting with the object. It enables us to change the internal implementation of a class without affecting other parts of the code that use the class, promoting modularity and code reusability.