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

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

问题描述

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

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 中,duck 类型提供抽象,闭包提供封装.(命名约定也可以提供封装,但这只有在所有各方都同意遵守的情况下才有效.)

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

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