In this article we learn the what is encapsulation in java, encapsulation in java example and what is getter and setter in java.
What is Encapsulation in Java?
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.
How to achieve encapsulation in Java?
Declare the variables of a class as private, so that they cannot be accessed directly from outside the class. Provide public setter and getter methods to modify and view the variables values.
Encapsulation in Java Example
In a large organization, there are so many departments like Sales, Accounts, Payroll, Purchase, Production, etc. Each department has its own staff that maintain its data.
Suppose an employee of the Production department wants to know the quantity of raw material that has been purchased for the next month. The employee would not be allowed to go through the data files of the Purchase dept.
Rather he will have to issue a memo to the ‘Purchase’ department requesting for the required information. Then respective employees of the Purchase department will go through the data files of Purchase and send the reply with the asked information.
This practice ensures that the users access the data accurately and the unexpert outsiders do not corrupt this data. Therefore, we can say that the ‘data and employees’ of the department encapsulate together into a single entity, the Department.
What is Getter and Setter in Java?
Getter and Setter in Java are two conventional methods used to retrieve and update values of a variable. They are mainly used to create, modify, delete and view the variable values. The setter method is used for updating values and the getter method is used for reading or retrieving the values. They are also known as an accessor and mutator.