Let’s see, What is Encapsulation in Java? Encapsulation is like creating a security layer for your instance variables rather than exposing it naked to the world.

Hope you would know about private, public access modifiers. Encapsulation is going to use private, public access modifiers to implement it. 

Encapsulation rule:

1. Mark your instance variable as private

2. Provide public getters and setters method for access control

When we declare variables as private, it means variable is accessible from the same class only. This is the most restrictive access modifier and is core to the concept of encapsulation in Java. All data will be hidden from the outside world.

What does Encapsulation do?

Encapsulation puts a force-field around instance variables i.e., mark variable as private, so that other class can never use it directly. Encapsulation forces other code to go through setter methods to set value and getter methods to access value of the instance variable.

Lets see an example for encapsulated class,

public class MarksHelper {

  private int mark;
  private String grade;

  public int getMark() {
    return mark;
  }

  public void setMark(int mark) {
    this.mark = mark;
    if (this.mark >= 90) {
      this.grade = "A";
    } 
    else if (this.mark >= 60 && this.mark < 90) 
    {
      this.grade = "B";
    } 
    else if (this.mark >= 40 && this.mark < 60) 
    {
      this.grade = "C";
    } 
    else 
    {
      this.grade = "D";
    }
  }

  public String getGrade() {
    return grade;
  }

}
public class MarksTester {

  public static void main(String[] args) {
    MarksHelper marksHelper = new MarksHelper();
    marksHelper.setMark(90);
    System.out.println("Grade: "+marksHelper.getGrade());
    marksHelper.setMark(65);
    System.out.println("Grade: "+marksHelper.getGrade());
    marksHelper.setMark(45);
    System.out.println("Grade: "+marksHelper.getGrade());
    marksHelper.setMark(35);
    System.out.println("Grade: "+marksHelper.getGrade());
  }
}

Output

Grade: A
Grade: B
Grade: C
Grade: D

In the above example MarksHelper class encapsulates mark, grade variables. As the variable mark, grade is made private, the variable cannot be used directly from other class. We should use getter, setter method to get Value, set Value respectively. MarksTester class is used to test the implemention of getter, setter method.

Conclusion

Encapsulation in Java, benefits us to validate data, control data, data hiding and easy to test data. We saw how to implement, create encapsulated class and test encapsulated class.

Please follow and like us: