6

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?

3
  • 2
    Did you read the Wikipedia article: en.wikipedia.org/wiki/… Apr 15, 2011 at 7:55
  • @Reno, Encapsulation doesn't means to just to protect data from modification. What if I added one more setter method.... based on your explanation, it means that encapsulation means read only properties of class ...which is not....i sure.... Apr 15, 2011 at 8:11
  • Also see: Why Properties Matter by Jon Skeet Apr 15, 2011 at 8:12

7 Answers 7

25

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:

  • Access control granularity; you can choose to make the value publicly read-only, read-write or write-only.
  • Possibility to validate input prior to storing the value
  • Possibility to add logging or other auditing mechanisms

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.

4
  • So does it means that adding a setter method to the property will break encapsulation? Apr 15, 2011 at 8:55
  • 2
    @anil: no, not at all. Encapsulation is about hiding implementation details. By having the field private and exposing it through methods, you encapsulate the internal implementation details. The value could be stored in a field, in a file on disk, in a database, it could be calculated on-the-fly, whatever. The calling code does (and should) not know such details. That is encapsulation. Apr 15, 2011 at 8:58
  • I guess hiding implementation details relates to abstraction not encapsulation. Now that sounds two different names are being used for the same term. look at this link : en.wikipedia.org/wiki/Abstraction_%28computer_science%29 Apr 18, 2011 at 7:16
  • @anil: I would say that encapsulation is a form of abstraction. This is also supported by the text you linked to: The term encapsulation refers to the hiding of state details (in the paragraph Abstraction in object oriented programming) Apr 18, 2011 at 8:55
3

Encapsulation separates the concept of what something does from how it is implemented.

Encapsulation is a very important concept in Object Oriented Programming. It is hiding the data from other modules in the application. In your example 2, as you can see you can only get the age and that too using a getter method, but you can only set the value to the private member within that class and not outside it. This is the advantage of Encapsulation.

2
  • 1
    how did polymorphism join this party?
    – GregC
    Apr 20, 2011 at 6:23
  • @GregC, oops! I meant it to be Encapsulation. Thanks for pointing it out. :) Apr 20, 2011 at 20:56
2

Think about this variant:

class Employee
{
    private int _age;

    public string Age
    {
        get { return _age.ToString(); }
    }
}

In your example the outside and inside use an integer and that is confusing. (Similar to showing 2 * 2 = 4 to explain multiplication and forgetting that 2 + 2 = 4 too)

2
  • @UGEEN, Erno, using same datatype inside and outside doesn't creates any confusion. That sound strange that you are converting it into string for many reason client may need it as integer. So is there any genuine reason to convert it to string..moreover how it helps encapsulation? Apr 15, 2011 at 8:59
  • The transformation to string is just to show that on the outside the type can be very different from the inside. Of course, when a client needs it as an integer the Age property should be of that type. The example is just to show that the property-get encapsulates (or can encapsulate) the inner dataformat.
    – Emond
    Apr 15, 2011 at 9:14
1

Encapsulation is data hiding simply.

let's see how encapsulation happens. Assume you create a Employee class and include two instance variables. name and salary. You don't make them private. Now what happens another class in the program can access these two variables simply by creating an object if the employee class. So what we want is to hide these both or salary information to outside classes.

If we want to hide salary We can simply declare salary as a private variable. Now we know even another class create an object and try to access salary as before it doesn't work. Because it is a private field which is only accessible to Employee class. Now we have hidden our data.

But assume that we need a person to enter salary details of each of the employees. I will make it more clear. The data entering person has 3 types of data to enter woked_hours, OT and leaves (Emplyee class has three variables for this). We want this person to enter these details but we do not want him to see how the salary calculation is done. It is done according to the mathematical equation which is inside Employee class.

So he cannot calculate and enter salary it self. But we let him see the final salary. there We create a method to get the value of the salary inside employee class. it is

public int getSalary()
{
   return salary;
} 

He knows this, that there are two methods he can use to access those hidden fields. set method and get method. So he call getmethod. yes he can see the salary information. Because we have created the getMethod to return salary. Now he try to use set method to enter a new salary amount to change current value of salary. so he call e.setSalary(1000); But it gives an error. Why? because in the employee class there is no method written as

   public void setSalary(int newSalary)
   {
   salary=newSalary;
   }

We intentionally didn't write that code because we don't want him to set salary value straight away. So we have hidden some information but some we still let him access. We gave him access to Read only. But not Write for salary.

so wasn't it useful now that encapsulation we have done.

The same way as he is allowed to set these fields woked_hours, OT and leaves . for those fields we have given him access to Write only. There we intentionally do not write getter methods. If you write both getter and setter you are allowing him to READ/ Write both access.

It doesn't matter only set or get, The field is private, the field is hidden already data is hidden. But some access is given through getters and setters .

0

In your first example the variable age is set as a public variable. Here anyone can modify the meeber age when an object of type Employee is declared.

However, in your second example the variable age is actually private, and can only be modified from inside of the class Employee. This is the case of data hiding.

In object oriented programming encapsulation is when one object is composed of another. This is in contrast to inheritance where an object can extent an already existing class.

1
  • As I had already commented in others response's, that is that you mean only one setter will break encapsulation. Do you mean that read-only properties can achieve encapsulation. I am sure it is not. As every one responded based on second method but what if a simple setter method is added? Apr 15, 2011 at 9:03
0

There is more to Encapsulation than data hiding. Encapsulation allows you to keep all the data and the functionality pertinent to an entity with this entity. Levels of visibility of this data is a related, but not identical, concept. E.g. an Employee object caries all employee data and functionality (methods) with it. Note that this is not enforced, but enabled by the OO languages.

This may sound natural to you if you were born into the OO era, but this was the big leap from Functional Programming to OOP, both conceptual (design) and in languages that support this paradigm.

Quoting from Wikipedia article:

In a programming language encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination thereof:

  • A language mechanism for restricting access to some of the object's components.
  • A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.
0

Say I use your code like this:

Employee employee = new Employee();
int age = employee.getAge();
// Do something with age

Here, unless I look at your source code, I have absolutely no idea how Employee has calculated its age. For all I know, getAge() could look like this:

public int getAge() {
    return new java.util.Random().nextInt( 100 );
}

or perhaps something even more complicated. I just don't know.

So in your second example, the fact that getAge() just returns a private member variable is completely hidden from me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.