Encapsulation in Java

Encapsulation combines data and methods into a single unit (class) and restricts direct access to the data from outside the class. It promotes data hiding and abstraction, allowing for better control and maintainability of the codebase.

Access Modifiers

Access modifiers in Java determine the accessibility of classes, fields, constructors, and methods. They enforce encapsulation by defining the scope of access to class members. There are four types of access modifiers in Java:

public: The member is accessible from any other class.
private: The member is accessible only within the same class.
protected: The member is accessible within the same class, subclass, and package.
Default (no modifier): The member is accessible within the same package.

Syntax
accessModifier dataType memberName;
Example
public class Person {
    private String name;
    protected int age;
    public String address;
    String email; // default access modifier

    // Constructor and methods omitted for brevity
}

In the above example, the name field is private and can only be accessed within the Person class. The age field is protected and can be accessed within the Person class, its subclasses, and the same package. The address field is public and can be accessed from any other class. The email field has default access and can be accessed within the same package.

Getter and Setter Methods

Getter and setter methods provide controlled access to the encapsulated data by encapsulating the logic to read and write the values. They allow for data abstraction and provide a layer of indirection between the data and the outside world.

Syntax
    
public returnType getPropertyName() {
    // Getter logic
}

public void setPropertyName(parameterType parameter) {
    // Setter logic
}

Example
    
public class Person {
    private String name;
    private int age;

    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;
        }
    }
}

In the above example, the getName() and setName() methods provide access to the private name field. Similarly, the getAge() and setAge() methods provide access to the private age field. The setter methods can include additional validation logic, as demonstrated in the setAge() method.

Conclusion

Encapsulation is a crucial concept in Java that promotes data hiding, data abstraction, and code maintainability. By using access modifiers and getter/setter methods, encapsulation allows for controlled access to class members and enhances the security and integrity of the data. Understanding and applying encapsulation effectively improves code organization and modularity in object-oriented programming.