DEV Community

Mohamed Ajmal
Mohamed Ajmal

Posted on

Encapsulation in Java

Encapsulation in Java is the process of wrapping data (variables) and the code that acts on that data (methods) together as a single unit, typically a class.

Encapsulation in Java is achieved using:

  1. Private data members,
  2. Public getter and setter methods.

Benefits:

Data Control: You can make a class read-only (by providing only getters) or write-only (by providing only setters).

Validation: Setters allow you to add logic to validate data before it is saved (e.g., ensuring an age is not negative).

Security: It protects sensitive internal states from unauthorized modification.

Maintainability: You can change the internal implementation of a class without breaking the code that uses it.

Example : class Programmer {

private String name;

public String getName() { return name; }

public void setName(String name) {

    this.name = name;
}
Enter fullscreen mode Exit fullscreen mode

}

public class Geeks {

public static void main(String[] args){

    Programmer p = new Programmer();
    p.setName("Geek");
    System.out.println("Name=> " + p.getName());
}
Enter fullscreen mode Exit fullscreen mode

}

Output: Name=> Geek

Top comments (0)