Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

.net - What is encapsulation? How does it actually hide data?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...