Tuesday, January 29, 2008

Encapsulation

ENCAPSULATION :
    Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.
Analogy:
Let's say we had one box containing one cake. There were 4 guys who wanted to eat that cake. If we kept the box open, any one could have eaten it,result would have been - No cake for others. How this situation was avoided ?

> we hired one person (guard), name getter. The responsibility of the person was to provide exact duplicate copy of the cake.
> we put a lock on the class and gave the key to guard. so no one can directly eat the cake, one has to ask getter for cake.

Bingo ! problem solved ??, Not yet; there was another issue that happened - I got the copy of cake and found that it was not sweet enough. I added the sugar and asked the guard to replace this cake with original one. Guard said - "that's not my duty". So we took another step:

> we hired one more person (guard), name setter. The responsibility of the setter was to replace the original cake.

I gave the new cake, with enough sweetness, to setter and he replaced it. Problem Solved ??, Not yet, one guy mixed the poison into cake and asked the setter to replace it.
So we were in problem again, so we took anothe step, we gave addition responsbility to setter -

> Test the cake before replacing. Replace it if and only if it passes certain test.
OK !! This is the concept behined ENCAPSULATION.In Technical terms -
>Box  act as Class 

>Cake act as Field of the class 
>guards act as public methods of the class 
>responsibilities of guards act as action performed by methods
So Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.

/*Encapsulation - This program has been build to illustrate the concept of encapsulation. Copyright (C) 2010  http://jovialjava.blogspot.com. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3 of the License. This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program.  If not, see http://www.gnu.org/licenses/. */


3 comments:

Anonymous said...

nice explanation Bro...!!!
but it will be better if u give some java syntax along with..!!

Anonymous said...

nice explanation bro..
it will be better if u provide some java syntax along with..!!!

Anonymous said...

You have got a good creative mind :D