Java中的抽象与封装 [英] Abstraction vs Encapsulation in Java

查看:89
本文介绍了Java中的抽象与封装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
抽象VS信息隐藏VS封装

Possible Duplicate:
Abstraction VS Information Hiding VS Encapsulation

我知道这个问题可能在这个论坛上被问过数千遍,即使net也充斥着很多关于这些概念的定义,但是听起来都一样,并且都使用了相同的技术性词汇.例如以下定义

I know this question might have been asked thousands times on this forum, even net is also filled with lots of definitions about these concepts but all sounds same and all uses same technical words. For example following definitions

封装是将数据和对数据进行操作的代码绑定或包装到单个实体中的过程.这样可以确保数据不受外部接口和滥用的影响.考虑封装的一种方法是作为一种保护性包装程序,以防止包装程序外定义的其他代码任意访问代码和数据.

Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.

我从上面的定义中了解到的是,创建变量,将其标记为私有并为这些变量生成getter-setter,并使用object访问这些getter和setter.这样,数据就隐藏在对象内部,并且只能通过对象访问. 希望我是对的.

What I understood from above definition is that creating variables, mark them private and generate getter-setter for those variables and use object to access those getter and setter. In that way data is hidden inside object and is only accessible through object. Hope I am right.

抽象是Java中的过程,用于隐藏某些细节并仅显示对象的基本功能.换句话说,它处理对象(接口)的外部视图.

Abstraction is the process in Java which is used to hide certain details and only show the essential features of the object. In other words, it deals with the outside view of an object (interface).

现在,这部分总是让我感到困惑.每当我想到抽象时,想到的就是Abstract类(可能是因为它们都有Abstract关键字).上面的定义说抽象意味着隐藏数据并仅显示必需的细节,但这就是我们在封装中已经在做的事情吧?那有什么区别另外,我没有在对象中处理对象的外部视图.

Now this is the part which confuses me always. Whenever I think about abstraction the thing which comes to my mind is Abstract class(may be because both have Abstract keyword). Above definition says abstraction means hiding data and only showing required details but that is what we are already doing in encapsulation right? then what is the difference. Also I did not get what is out side view of object in it deals with the outside view of an object.

有人可以通过一些现实生活中的示例或一些编程性示例来对此进行更多说明吗?

Can someone please put more light on this with some real life example or with some programmatic examples if possible.

推荐答案

OO抽象 发生在类级别设计中,目的是隐藏如何 API/design/提供的功能的实现复杂性在某种意义上简化了系统以访问底层实现的接口".

OO Abstraction occurs during class level design, with the objective of hiding the implementation complexity of how the the features offered by an API / design / system were implemented, in a sense simplifying the 'interface' to access the underlying implementation.

抽象过程可以在类的更高"级别(层)上重复进行,从而可以构建大型系统而无需增加代码的复杂性和每一层的理解.

The process of abstraction can be repeated at increasingly 'higher' levels (layers) of classes, which enables large systems to be built without increasing the complexity of code and understanding at each layer.

例如,Java开发人员可以利用 FileInputStream 无需担心其工作原理(即文件句柄,文件系统安全性检查,内存分配和缓冲将在内部进行管理,并且对使用者不可见).这样就可以更改FileInputStream的实现,并且只要FileInputStream的API(接口)保持一致,针对以前版本构建的代码仍然可以使用.

For example, a Java developer can make use of the high level features of FileInputStream without concern for how it works (i.e. file handles, file system security checks, memory allocation and buffering will be managed internally, and are hidden from consumers). This allows the implementation of FileInputStream to be changed, and as long as the API (interface) to FileInputStream remains consistent, code built against previous versions will still work.

类似地,在设计自己的类时,您将希望尽可能地向其他人隐藏内部实现细节.

Similarly, when designing your own classes, you will want to hide internal implementation details from others as far as possible.

在Booch定义 1 中, OO封装是通过

In the Booch definition1, OO Encapsulation is achieved through Information Hiding, and specifically around hiding internal data (fields / members representing the state) owned by a class instance, by enforcing access to the internal data in a controlled manner, and preventing direct, external change to these fields, as well as hiding any internal implementation methods of the class (e.g. by making them private).

例如,默认情况下可以将类的字段设置为private,并且仅当需要从外部访问这些字段时,才会从以下位置公开get()和/或set()(或Property)班级. (在现代的OO语言中,字段可以标记为readonly/final/immutable,这甚至进一步限制了更改,即使在类内也是如此).

For example, the fields of a class can be made private by default, and only if external access to these was required, would a get() and/or set() (or Property) be exposed from the class. (In modern day OO languages, fields can be marked as readonly / final / immutable which further restricts change, even within the class).

未应用任何信息隐藏功能的示例(不良做法):

class Foo {
   // BAD - NOT Encapsulated - code external to the class can change this field directly
   // Class Foo has no control over the range of values which could be set.
   public int notEncapsulated;
}

已应用字段封装的示例:

class Bar {
   // Improvement - access restricted only to this class
   private int encapsulatedPercentageField;

   // The state of Bar (and its fields) can now be changed in a controlled manner
   public void setEncapsulatedField(int percentageValue) {
      if (percentageValue >= 0 && percentageValue <= 100) {
          encapsulatedPercentageField = percentageValue;
      }
      // else throw ... out of range
   }
}

字段不变/仅构造函数初始化的示例:

class Baz {
   private final int immutableField;

   public void Baz(int onlyValue) {
      // ... As above, can also check that onlyValue is valid
      immutableField = onlyValue;
   }
   // Further change of `immutableField` outside of the constructor is NOT permitted, even within the same class 
}

Re:抽象与抽象类

抽象类是促进类之间公共性重用的类,但它们本身不能直接被使用用new()实例化-必须对抽象类进行子类化,并且只能实例化concrete(非抽象)子类. Abstractionabstract class之间可能造成混淆的一个原因是,在OO的早期,继承被更多地用于实现代码重用(例如,与相关的抽象基类一起使用).如今,组合通常优于继承,并且有更多工具可用于实现抽象,例如通过接口,事件/委托/功能,特征/mixins等.

Abstract classes are classes which promote reuse of commonality between classes, but which themselves cannot directly be instantiated with new() - abstract classes must be subclassed, and only concrete (non abstract) subclasses may be instantiated. Possibly one source of confusion between Abstraction and an abstract class was that in the early days of OO, inheritance was more heavily used to achieve code reuse (e.g. with associated abstract base classes). Nowadays, composition is generally favoured over inheritance, and there are more tools available to achieve abstraction, such as through Interfaces, events / delegates / functions, traits / mixins etc.

回复:封装与信息隐藏

封装 的含义似乎随着时间的流逝而发展,在最近一段时间,

The meaning of encapsulation appears to have evolved over time, and in recent times, encapsulation can commonly also used in a more general sense when determining which methods, fields, properties, events etc to bundle into a class.

引用维基百科:

在面向对象编程语言的更具体设置中,该概念用于表示信息隐藏机制,捆绑机制或两者的组合.

In the more concrete setting of an object-oriented programming language, the notion is used to mean either an information hiding mechanism, a bundling mechanism, or the combination of the two.

例如,在语句

我已经将数据访问代码 封装了

I've encapsulated the data access code into its own class

.. 封装的解释大致等同于关注点分离单一责任主体(在SOLID中为"S"),可以说是用作重构的同义词.

.. the interpretation of encapsulation is roughly equivalent to the Separation of Concerns or the Single Responsibility Principal (the "S" in SOLID), and could arguably be used as a synonym for refactoring.

[1] 一旦您看到了Booch的

[1] Once you've seen Booch's encapsulation cat picture you'll never be able to forget encapsulation - p46 of Object Oriented Analysis and Design with Applications, 2nd Ed

这篇关于Java中的抽象与封装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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