Encapsulation in java with example

Encapsulation in java is the process of binding related data(variables) and functionality(methods) into a single unit called class. Encapsulation can be achieved by using access modifier such as public, private, protected or default, so your class will be safe from unauthorized access by others and will be simple to maintain.

We can create fully encapsulated class by

  • Making variables private
  • Providing getters and setters methods for the accessing the variables.

Encapsulation is also termed as data hiding because you are making variables private and variables can be only accessed through public getters and setters.

Example of Encapsulation in java:

When you run above program, you will get below output:

=============
Employee Id: 1
Employee Name: John
Employee Department: Sales

Advantages of Encapsulation in java:

  • It provides control over data. For example: If You want to check if age of employee is greater than 18 in setter method(setAge(int age)). You can easily do it in setter method without breaking any code.
  • Increase reusability.
  • Makes class easy to use for other clients.
  • It helps the developer to write code more flexible and maintainable by binding them into a single unit and use appropriate access modifier to access the code as per need.

Difference between abstraction and encapsulation in java:

  • Encapsulation means data hiding using getter and setters. Abstraction means hiding implementation details using [abstract class](https://java2blog.com/abstract-class-java/ “abstract class”) and [interface](https://java2blog.com/interface-in-java-with-example/ “interface”).
  • Abstraction is more of design level concept and Encapsulation is more of implementation level concept.

That’s all about encapsulation in java.

Was this post helpful?

Leave a Reply

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