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 excessed 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 and interface.
  • Abstraction is more of design level concept and Encapsulation is more of implementation level concept.

 

Add Comment