Encapsulation in JAVA

Table of Contents

Encapsulation :

Sometimes we have to declare some variables with private access specifier, specially variables which stores sensitive values e.g. ID, Name, BankBalance, AccountNumber, etc.
So we will keep such variables private, but now no other class can access it or assign value to this private variable.
So question arise is “How to assign value to the private variable?” and “How to fetch value from it?”.
So the solution is to create public methods which can be use to assign value to private variable and to fetch value from it. Those methods are get() and set().
The above scenario is as example of Encapsulation. We can hide sensitive variables from others. In Encapsulation we will define two methods by using these methods other can get and set values to private variable. This increases security. It is also known as data hiding.

get method :

As the name suggest get method is use to fetch the value of private variable.
It is declared public which helps other class to fetch the value of private variable.
Rules For get method :
* get method must be declare with public access specifiers.
* get method can’t have void return type.
* get method return type must be same as the private variable which value it is going to return.
* get method must be define with empty parameters.

set method :

As the name suggest set method is use to assign value to the private variable.
It is declared public which helps other class to assign the value to private variable.
Rules For set method :
* set method must be declare with public access specifiers.
* get method must have void return type.
* get method must accept exact one value from parameters which has same data type as the private variable which is going to be initialize.

“this” keyword :

Here “this” keyword is use to specify that the variable is instance variable.
In below example accountnumber is a private variable which will get assign with help of setAccountnumber(String accountnumber).
We can see that local variable name is same as the instance variable’s so now if we want to assign value of local variable to instance variable we have to distinguish between them.
This is done by using “this” key word e.g. this.accountnumber = accountnumber.

Leave a Comment