Encapsulation
The Blog will give a real world example to better understand encapsulation.
Consider you have 500 rupees someone walks to you
can't talk money from so ask you to give money. Then you have your money encapsulated in you. ( protect your money by putting it in a secure wallet )
can take money from your pocket then your money is not encapsulated. ( holding money in hand)
You may wonder how this relates to OOPS and What encapsulated means.
Encapsulation in OOPS : Wrapping properties and methods in a class to restrict direct access to data in the class. In simple we put or wrap data in a unit to protect it from the external world.
Now we try to relate the example with the definition. In the first scenario, you are restricting direct access to money by putting/ encapsulating it inside a wallet or locker so he/she can't take money. while in the second scenario, you are holding the money in public which he/she can easily take. To understand better see the below implementation of both scenario codes.
First scenario :
public class Human{
public double money;
}
Human You = new Human();
You.money = 0 ; // Direct access of data.
Second scenario :
public class Human{
private double money;
public double getMoney(){
return money;
}
public void setMoney(double money){
this.money = money;
}
// We can now decide whether to make getMoney() and setMoney() public or
// private to restrict control
}
Human You = new Human();
// We can't directly access the money as it is private. we need to access
// using method or actions
You.getMoney();
You.setMoney();
I hope you enjoyed relating OOPs concept with real-world examples. If you have feedback comment below : )