Encapsulation is one of the four fundamental concepts (Encapsulation, Inheritance, Polymorphism, and Abstraction) in Java OOP. It is a mechanism to bundling data (variables) and code that works upon them (methods) into a single unit. By encapsulating attributes, other class cannot access them, they can only be accessed by the methods within the class. This concept helps in hiding the internal state of an object and only exposing necessary functionalities through public methods. By encapsulating data, Java ensures better data security and code maintainability.

Need for encapsulation

  • Data hiding
    • The internal state of an object is hidden from the outside. Direct access to the object’s data is restricted
    • This can be achieved by declaring the data members of a class as private
  • Access control and validation
    • Controlled access to the class data is provided through public methods (getters and setters)
    • These methods allow for validation, conditional access, or transformation of data before it is set or returned.
  • Improve maintainability
    • Encapsulation makes the code easier to maintain and modify. Changes to the internal implementation do not affect the external code that uses the class.

Example

public class Person {
    // private fields
    private String name;
    private int age;
    
    // public getter for name
    public String getName() {
        return name;
    }
    
    // public setter for name
    public void setName(String name) {
        this.name = name;
    }
    
    // public getter for age
    public int getAge() {
        return age;
    }
    
    // public setter for age with validation
    public void setAge(int age) {
        if (age > 0) {
            this.age = age;
        } else {
            System.out.println("Age must be positive.");
        }
    }
}
 
public class Main {
    public static void main(String[] args) {
        Person person = new Person();
        
        // setting values using setters
        person.setName("John Doe");
        person.setAge(25);
        
        // getting values using getters
        System.out.println("Name: " + person.getName());
        System.out.println("Age: " + person.getAge());
    }
}
  • Private field
    • The Person class has two private fields: name and age. These fields are not accessible directly from outside the class.
  • Public Getters and Setters
    • The class provides public methods (getName, setName, getAge, setAge) to access and modify the private fields.
  • Data validation
    • The setter for age includes validation logic to ensure that the age is positive. This ensures that the internal state remains consistent and valid.

Back to parent page: Java Standard Edition (Java SE) and Java Programming

Web_and_App_DevelopmentProgramming_LanguagesJavaOOPEncapsulation

Reference: