Encapsulation in Java

Encapsulation in Java is a mechanism of wrapping up the data (variables) and behavior (methods) together in one single unit (Class).

In Encapsulation, the variables of a class will be hidden from the other classes, and can only be accessed through the methods of the current class in which they are declared.

As in encapsulation, the data in a class is hidden from another class, so it is also known as data-hiding.

How can you achieve Encapsulation?

  • By defining the variables in a class as private. As private variables are not accessible outside the class, you can define getters and setters to read and write the values of these variables.
  • Getters and Setters are the standard names given to the methods which are used to read and write the values of private members.
  • Getters and Setters can make variable read-only or write-only.
  • Using getters and setters for the private variables also gives you an ability to protect variables from the unauthorized access.

Consider the below example to understand the concept:

Let us create a class Employee which has two variables salary and bonus of type int and a method to calculate salary and if you have defined them as public variables if someone gets an unauthorized access to this variable from outside, they can easily modify the values (can put a negative value) which is not correct ( a salary cannot have a negative value)

Now if define the variables as private then we will be using getters and setters method to read and write the values. To stop the unauthorized access and modification of data you have control in your setter method and can put all the necessary conditions.

See below code:

PS: For any questions, queries or feedback. Feel free to write us at saurabh@qatechhub.com or support@qatechhub.com

Saurabh Dhingra

About the Author

Saurabh Dhingra

Follow Saurabh Dhingra: