什么是封装?它实际上如何隐藏数据? [英] What is encapsulation? How does it actually hide data?

查看:33
本文介绍了什么是封装?它实际上如何隐藏数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

搜索有一个简单的定义:数据隐藏.

Searching turns up a simple definition: data hiding.

但是,请考虑以下两个示例:

But, consider the following two examples:

1) 第一个例子:

Class Employee
{
    public int age;
}

2) 第二个例子:

Class Employee
{
    private int age;

    public int getAge(){return age;}
}

问题:
上述两个例子中,没有数据隐藏,因为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?

推荐答案

数据隐藏.第二个示例隐藏了如何存储值.此外,第二个示例使该值对于类外的代码为只读.通过拥有私有字段并通过方法或属性公开它们,您可以立即获得一些优势,其中一些优势是:

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.

这篇关于什么是封装?它实际上如何隐藏数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆