抽象和封装之间有什么区别? [英] What's the difference between abstraction and encapsulation?

查看:181
本文介绍了抽象和封装之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在访谈中,我被要求解释抽象和封装之间的区别.我的回答一直是

In interviews I have been asked to explain the difference between abstraction and encapsulation. My answer has been along the lines of

  • 抽象使我们能够以最简单的方式表示复杂的现实世界.这是确定对象应具备的相关素质和行为的过程;换句话说,在不表示背景细节的情况下表示必要的功能.

  • Abstraction allows us to represent complex real world in simplest manner. It is the process of identifying the relevant qualities and behaviors an object should possess; in other words, to represent the necessary feature without representing the background details.

封装是一个将对象的所有内部细节从外界隐藏起来的过程. 封装"一词就像封装"到胶囊"中一样.它限制了客户查看其内部视图的位置,在该视图中实现了抽象的行为.

Encapsulation is a process of hiding all the internal details of an object from the outside real world. The word "encapsulation", is like "enclosing" into a "capsule". It restricts clients from seeing its internal view where the behavior of the abstraction is implemented.

我认为上面的回答使访调员深信不疑,但是随后我被问到,如果两者的目的都是隐藏的,那么为什么需要使用封装.当时我对此没有很好的答案.

I think with above answer the interviewer was convinced, but then I was asked, if the purpose of both is hiding, then why there is a need to use encapsulation. At that time I didn't have a good answer for this.

我应该添加些什么以使答案更完整?

What should I have added to make my answer more complete?

推荐答案

抽象与将接口与实现分开. (我们不在乎是什么,我们不在乎它以某种方式工作.)

Abstraction has to do with separating interface from implementation. (We don't care what it is, we care that it works a certain way.)

封装与禁止访问或不了解实现的内部结构有关. (我们不在乎,或者只需要看一下它是如何工作的.)

Encapsulation has to do with disallowing access to or knowledge of internal structures of an implementation. (We don't care or need to see how it works, only that it does.)

有些人确实使用封装作为抽象的同义词,这是(IMO)不正确的.您的面试官可能会想到这一点.如果真是这样,那么当您提到封装"时,你们每个人都在谈论两种不同的事物.

Some people do use encapsulation as a synonym for abstraction, which is (IMO) incorrect. It's possible that your interviewer thought this. If that is the case then you were each talking about two different things when you referred to "encapsulation."

值得注意的是,这些概念在不同的编程语言中有不同的表示.一些例子:

It's worth noting that these concepts are represented differently in different programming languages. A few examples:

  • 在Java和C#中,接口(在某种程度上还包括抽象类)提供抽象,而访问修饰符提供封装.
  • 在C ++中,这几乎是相同的,只是我们没有接口,只有抽象类.
  • 在JavaScript中,鸭子类型提供抽象,而闭包则提供封装. (命名约定也可以提供封装,但是只有在所有各方都同意遵循封装的情况下,这种封装才有效.)

这篇关于抽象和封装之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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