Encapsulation in Java OOPs

Java Encapsulation is one of the key oops concept and its nothing but binding the code and data member in a single unit. It’s also called as data-binding. The best example of encapsulation is class.

Many design patterns are implemented on the basis of encapsulation. Encapsulation mechanism protect data member of class against external access, it’s nothing but protect against external unauthorized access.

How can we create fully encapsulated class?

We need make all data member as private and create a getter and setter for accessing the value of data member. POJO is the best example of fully encapsulated class.

As above example, we can see the class Student that all the data member (variable) are declared as the private scope and also we created getter and setter for those members in a class, by using getter and setter we can able to change or retrieve the value of data members respectively.

Encapsulation helps the developer to make the code more flexible and maintainable by binding related data in a single unit and access/restrict that using appropriate access modifier. With well encapsulation implementation, one can change one part of the code easily without affecting the other part of the code. Java provides their important access specifiers to provide the scope of class data members and methods. This is given below.

  • Private
  • Public
  • Protected

Advantages of encapsulation

  • Encapsulation gives more flexibility and easy to change the code with the new requirement.
  • U can make a class as read-only by using getter and setter.
  • Encapsulation gives us to change one part of code without affecting another part of the code.
  • Encapsulation gives us Reusability.
  • Encapsulation gives control over the code.

Related Posts:-

4 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Show Buttons
Hide Buttons