Concept of Encapsulation in Java explained

Concept of Encapsulation in Java :

Encapsulation is one of the Object Oriented Programmingfundamental means wrapping (encapsulating) up of data or fields in a single method, make each field private and give the access of method to users (by making the method public) and in this way we can save each field from outside world.

 

If we provide each single data to outside world than anyone can change its values which will result in breaching of security.

 

Encapsulation is sometimes called Data Hiding that means we hide single field and provide the method to user for accessing that data or field.

 

To understand encapsulation see the diagram shown below :

 



Why we need Encapsulation :

Encapsulation is needed to restrict the access of raw data to outside world. To understand this statement, let’s take an example :

 

Suppose I have a bank account which is maintained on a software system and if I want to do a transaction than I can directly access all the variables relating to the account.

 

Let’s say there is a field, myBalance of integer type which is public. Now I can change or access its value by the object of Account class.

 

Now, consider the case when I withdraw some cash from my account, say 500 than I have to change the value of myBalance by decreasing the amount by 500 by this statement :

 

obj.myBalance = myBalance – 500; // where obj is an object of type Account.



If I can directly access this variable than rather subtracting this amount, I can add double of that amount to myBalance or even add any balance that I want by the use of below statement :

 

obj.myBalance = myBalance + 1000;



That means I can freely change my balance which results in big loss to banks and here the concept of Encapsulation comes into the picture.

 

Through the use of encapsulation we can provide debit method to user and credit method to user for withdrawing cash and crediting cash respectively in account and also make the variable myBalance private.

 

For e.g.

 

private int myBalance;

public int debitCash(int cash) {

myBalance = myBalance – cash; return myBalance;

}

public int creditCash(int cash) {

myBalance = myBalance + cash; return myBalance;

}

 

I hope you guys are clear that why we use encapsulation.

 

Related blog:

 

java training institute in chennai