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

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

问题描述

搜索变成了一个简单的定义:数据隐藏

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;}
}

问:
在上述两种实施例中指定,没有数据隐藏,如年龄是由他人修改或由他人正在观看。在哪里数据隐藏?如何在上述的实施例做封装帮助?

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?

推荐答案

目前的的数据隐藏。第二个例子隐藏的如何的值存储。另外,第二个例子中,使只读类外code的值。通过让私人领域,并通过方法或属性揭露他们,你立即获得一些优势,其中有些是:

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:

  • 访问控制粒度;您可以选择使价值公开只读,读写或只写。
  • 的可能性,以验证输入存储值之前,
  • 可能性添加日志记录或其他审核机制

请注意,封装不仅是有访问控制。用于封装的主要用途是的隐藏实现细节与调用code 的。当调用code想要检索的值,它不应该依赖于的从那里的价值来。在内部,类可以存储该值在字段或检索它从一些外部资源(如文件或数据库)。的或许值不存储在所有的,但计算即时。这不应该的问题,以调用code。

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.

当您完成一个方法或属性暴露值,则屏蔽呼叫从这些细节,这也让您可以更改执行code,而不影响调用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天全站免登陆