Searching turns up a simple definition: data hiding.
But, consider the following two examples:
1) First Example:
Class Employee
{
public int age;
}
2) Second Example:
Class Employee
{
private int age;
public int getAge(){return age;}
}
Question:
In both the above specified examples, there is no data hiding, as age
is either being modified by others or being viewed by others. Where is the data hiding? How does encapsulation help in the above examples?
As in encapsulation, the data in a class is hidden from other classes using the data hiding concept which is achieved by making the members or methods of a class private, and the class is exposed to the end-user or the world without providing any details behind implementation using the abstraction concept, so it is ...
Encapsulation is a way to restrict the direct access to some components of an object, so users cannot access state values for all of the variables of a particular object. Encapsulation can be used to hide both data members and data functions or methods associated with an instantiated class or object.
Data encapsulation, also known as data hiding, is the mechanism whereby the implementation details of a class are kept hidden from the user.
There is data hiding. The second example hides how the value is stored. Also, the second example makes the value read-only for code outside the class. By having private fields and exposing them through methods or properties you immediately gain some advantages, some of which are:
Note that encapsulation is not only about having access control. The primary use for encapsulation is to hide implementation details from calling code. When calling code wants to retrieve a value, it should not depend on from where the value comes. Internally, the class can store the value in a field or retrieve it from some external resource (such as a file or a database). Perhaps the value is not stored at all, but calculated on-the-fly. This should not matter to the calling code.
When you expose the value through a method or property, you shield calling code from such details, which also gives you the possibility to change the implementation, without affecting calling code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With