What is the difference of having the instance variable as public and allowing to be accessed and above encapsulation.
This difference is that client objects do not directly access the variable. Instead client objects "ask" the object for it by calling a method and the object gives it the value. This is beneficial in many ways, especially in cases where variables types may change or if additional logic later needs to be added to the action of providing the value to client objects. This form of encapsulation fosters flexibility and makes code more agile.
Data is more secure in the sense that data can be accessed in a safe way - the same way your bank account is secure because it can be accessed in a safe way. In some classes, there are rules for accessing data so that the class is always in a consistent state. These rules can be defined in a method and everyone is forced to comply with these rules by making the data private and the method public. It's like saying if you want to access this data, you must first comply with these rules. If everyone was allowed to directly access the data without complying with the rules, there is a good chance that the class will be left in an inconsistent state.
Encapsulation also has the advantage that the rules can be modified without having to modify every client.
Senthil Kumar Sekar wrote:Encapsulation is achieved by marking the instance variables to private and providing access thru public accessor and mutator methods.
That's true, but it is far from being a description of encapsulation. It's simply a rather trivial example of encapsulation in action.
So asking questions about that example and drawing conclusions about encapsulation doesn't make sense. It's like saying "Nepal is a country" and then drawing conclusions about all countries based on what you know about Nepal.
Joined: Apr 16, 2008
Good point Paul. The sentence is poorly written. To be more concise, it could have been written as:
One common method of implementing "encapsulation" is to declare instance variables as private and provide access through public accessor and mutator methods.
i would like to add one point
by making instance variables private we can protect them from assigning them to unwanted values . In public accessor method (in setters) we can
add the code to check for allowed values.
For example, for a student we do not want to set its roll no to a negative value