This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
jose chiramal wrote: instead of private variables can I have access specifier as protected ? Will it still be encapsulation ?
As far I know, Encapsulation is Specific to a class , another class(say user) dont have the rights to change/affect the data(encapsulation). if you make the variable as protected,it visible to a user(if he extends that class), which violate encapsulation. when you say protected, it is mostly related to an Abstraction
encapsulation will "shield" your instance variables (state)
say you have an Animal object (class), that may have ints for "eyes", "legs" and so on
You dont want to be setting these values directly elsewhere in your application, for example you dont (but can) want to do:
Animal a = new Animal();
a.eyes = 2
Thats not nice, you want to use encapsulation to shield that variable. So you would have accessors (getters and setters) which will set/retrieve the values for you, so you can say:
Animal a = new Animal();
a.setEyes(2);
That means that every time you set the number of eyes, it goes thru that accessor.
Another better example may be if you have a House object, such as :
House h = new House();
h.setPostcode("ABC123");
At least then, on your setPostcode method(accessor) in your House class, you could introduce a regex, or to format to upper or lower case etc. It introduces a single point of failure, so providing everyone uses the acessors, they should be guaranteed to get the behaviour they expected