Encapsulation

Introduction

Encapsulation means wrapping code and data together into a single unit. Encapsulation is also used for data hiding. But the main purpose of encapsulation is to bind the data together in a single unit.

class Area {

  // fields to calculate area
  int length;
  int breadth;

  // constructor to initialize values
  Area(int length, int breadth) {
    this.length = length;
    this.breadth = breadth;
  }

  // method to calculate area
  public void getArea() {
    int area = length * breadth;
    System.out.println("Area: " + area);
  }
}

class Main {
  public static void main(String[] args) {

    // create object of Area
    // pass value of length and breadth
    Area rectangle = new Area(5, 6);
    rectangle.getArea();
  }
}

In the above example, the area is calculated. This is an example of encapsulation. Data hiding is only possible if both fields are private.

Data hiding

Data hiding means hiding the implementation. The capsule is the easiest and most real-life example of encapsulation as data hiding. How many medicines mix in the capsule no one knows. Only the maker knows what is in a capsule. Making fields private and make getter, setter public. Restrict the others to access fields. This is called data hiding.

class Student {

  // private field
  private int studentId;

  // getter method
  public int getstudentId() {
    return studentId;
  }

  // setter method
  public void setstudentId(int studentId) {
          if(studentId>0) {
        this.studentId = studentId;
      }
    }


class Main {
  public static void main(String[] args) {

    // create an object of Student
    Student s1 = new Student();

    // change age using setter
    s1.setstudentId24);

    // access age using getter
    System.out.println("My studentID is " + s1.getstudentId());
  }
}

We have to create the studentId and do not want other programmers to store the negative value or zero in the field. The solution is to make the setter of the studentId and write the logic in it. Mark studentId as a private modifier and make setter public. Outer classes can only access using the setter method. In the future, if the coder needs to replace or write something new. We can achieve this without breaking the other's code.