Encapsulation

Encapsulation is the technique of making the fields in a class private and providing access to them via public methods. It helps in protecting the data and ensures the data is accessed only in the ways the designer intended.

How Encapsulation Works

Encapsulation is implemented using access modifiers:


public class Person {
    // Private fields
    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;
        }
    }
}
      

In this example, the fields name and age are private and can be accessed only through the public getter and setter methods.

Benefits of Encapsulation

  • Control – The class has control over the data and can restrict unauthorized access.
  • Flexibility – The implementation can be changed without affecting other parts of the code.
  • Data Hiding – The internal representation of an object is hidden from the outside view.

Continue exploring our intermediate tutorials to learn more about Java programming.

Scroll to Top