13

根据 http://www.cs.cornell.edu/courses/cs211/2006sp/Lectures/L08-abstraction/08_abstraction.html

抽象有两种形式。一是函数抽象,二是数据抽象。但是抽象类在哪里适合呢?据我所知,抽象类是一个完全不同的概念,尽管名称暗示它与 OOP 原则有关。

有人可以对此有所了解吗?

4

3 回答 3

12

这些是非常不同的概念。

抽象类似于黑盒的概念。输入进去,黑盒做点什么,输出出来。黑匣子里发生了什么并不重要,你只需要知道它是有效的。一个真实的例子是java的散列函数,用户只需要知道它对输入值进行散列,对于用户如何散列数字并不重要。黑匣子是抽象的。关键是您不必知道它是如何工作的,只要知道它就知道。

抽象类(至少在 Java 中)是接口和完整 OOP 类的混合体。接口定义了任何扩展类必须具有的方法,它在代码中约定它将正确实现接口并确保一切都按预期工作。抽象类具有这些空方法(协议),并且还具有可以调用的完全实现的方法。

于 2012-09-26T03:00:28.977 回答
4

Data abstraction is a different concept from an abstract class.

Data abstraction - It means hiding the implementation and showing only essential information. Practically, we can use access-specifiers like public, private, protected, etc to achieve abstraction. For eg, Private functions/variables cannot be used accessed outside the class. Abstraction is simply 'hiding'. You can refer geeksforgeeks for more details.

Abstract class - Abstract classes/methods are created so that it can be implemented in its subclasses because the abstract class does not know what to implement in the method but it knows that the method will exist in its subclass. So, while we creating subclass we need to override the abstract method to provide its implementation.

于 2020-08-13T10:39:07.410 回答
0

对象通常将数据与功能结合起来,抽象类也不例外。在某些情况下,提供的抽象几乎是纯数据,其功能仅用于提供对数据的访问(例如,集合类)。其他情况几乎相反(例如,C++ 中函子提供的抽象通常几乎是一个函数)。

当然,这些几乎是极端的——许多(大多数?)类介于它们之间。

于 2012-09-26T02:56:15.043 回答