封装和抽象之间的确切区别是什么?


当前回答

抽象是我们将要执行的实现的契约。实现可能会在一段时间内发生变化。各种实现本身可能隐藏,也可能不隐藏,而是隐藏在抽象后面。

假设我们在一个接口中定义了一个类的所有api,然后要求代码的用户依赖于该接口中定义的api。我们可以自由地改进或修改实现,但必须遵守设定的合同。用户与我们的实现没有耦合。

我们在抽象中暴露所有必要的规则(方法),规则的实现留给实现者实体,实现也不是抽象的一部分。正是签名和声明使抽象成为现实。

封装只是通过减少对状态和行为的访问来隐藏内部细节。封装的类可能有也可能没有定义良好的抽象。

java.util.List是java.util.ArrayList的抽象。使用非公共访问修饰符标记的java.util.ArrayList的内部状态是封装。

Edit Suppose a class Container.nava implements IContainer , IContainer may declare methods like addElement, removeElements, contains, etc. Here IContainer represents the abstraction for its implementing class. Abstraction is declaring the APIs of the class or a module or a system to the outer world. These APIs become the contract. That system may be or may not be developed yet. The users of the system now can depend on the declared APIs and are sure any system implementing such a contract will always adhere to the APIs declared, they will always provide tge implementation for those APIs. Once we are writing some concrete entity then deciding to hide our internal states is encapsulation

其他回答

简而言之:

抽象是一种帮助我们识别哪些特定信息是必要的,哪些信息应该隐藏的技术。

因此,封装是一种以隐藏对象的细节和实现细节的方式封装信息的技术。

下面这段话帮助我理解了它们之间的区别:

数据封装是一种捆绑数据的机制 使用它们的函数和数据抽象是一种机制 只暴露接口,隐藏实现细节 来自用户。

你可以在这里阅读更多。

封装是将复杂性包裹在一个胶囊中,即类&因此封装… 抽象是一个对象区别于其他对象的特征。

抽象可以通过使具有一个或多个抽象方法的类抽象来实现。它只是一个特性,应该由扩展它的类来实现。 例如,当你发明/设计一辆汽车时,你定义了一个特征,比如汽车应该有4个门、刹车、方向盘等,所以任何使用这种设计的人都应该包括这些特征。实现并不是抽象的首要部分。它只会定义应该包含的特征。

Encapsulation is achieved keeping data and the behaviour in one capsule that is class & by making use of access modifiers like public, private, protected along with inheritance, aggregation or composition. So you only show only required things, that too, only to the extent you want to show. i.e. public, protected, friendly & private ka funda…… e.g. GM decides to use the abstracted design of car above. But they have various products having the same characteristics & doing almost same functionality. So they write a class which extends the above abstract class. It says how gear box should work, how break should work, how steering wheel should work. Then all the products just use this common functionality. They need not know how the gear box works or break works or steering wheal works. Indivisual product can surely have more features like a/c or auto lock etc…..

两者都很强大;但是使用抽象需要比封装更多的技能,没有抽象,更大的应用程序/产品就无法生存。

封装意味着隐藏数据,比如使用getter和setter等。

抽象意味着-隐藏实现使用抽象类和接口等。

抽象让您关注对象做了什么,而不是它是如何做的 封装意味着隐藏对象如何做某事的内部细节或机制。

就像你开车时,你知道油门踏板的作用,但你可能不知道它背后的过程,因为它是封装的。

让我用c#举个例子。假设你有一个整数:

int Number = 5;
string aStrNumber = Number.ToString();

你可以使用像number . tostring()这样的方法,它返回数字5的字符表示,并将其存储在字符串对象中。该方法告诉您它做了什么,而不是如何做。