java - 没有任何实现和变量的抽象类是有效的接口(interface)吗?

标签 java python oop inheritance design-patterns

我正在复习 OOP 的概念,正在阅读。

这里本书将接口(interface)定义为

The set of all signatures defined by an object’s operations is called the interface to the object. (p.39)

抽象类为

An abstract class is one whose main purpose is to define a common interface for its subclasses. An abstract class will defer some or all of its implementation to operations defined in subclasses; hence an abstract class cannot be instantiated. The operations that an abstract class declares but doesn’t implement are called abstract operations. Classes that aren’t abstract are called concrete classes. (p.43)

我想知道,如果我定义一个没有任何内部数据(变量)和具体操作的抽象类,只有一些抽象操作,它实际上不是只是一组签名吗?那么它不就是一个接口(interface)吗?

这是我的第一个问题:

  1. 我可以说只有抽象函数的抽象类“有效(或理论上)”是一个接口(interface)吗?

然后我想,这本书还讲了一些关于类型和类的内容。

An object’s class defines how the object is implemented. The class defines the object’s internal state and the implementation of its operations. In contrast, an object’s type only refers to its interface—the set of requests to which it can respond. An object can have many types, and objects of different classes can have the same type. (p.44)

然后我想起有些语言,比如Java,不允许多重继承,但允许多重实现。所以我猜想对于某些语言(如Java),只有抽象操作的抽象类!=接口(interface)。

这是我的第二个问题:

  • 我可以说只有抽象函数的抽象类“通常等同于”支持多重继承的语言中的接口(interface)吗?
  • 我的第一个问题是检查定义,第二个问题是关于其他语言如何工作。我主要使用 Java 和 Kotlin,所以我不太确定其他支持多重继承的语言。我不期望对当前的 OOP 语言进行一般性、全面的回顾,但只是对单一语言(也许是 python?)的一点提示将会非常有帮助。

    最佳答案

    1. 没有。

    在 Java 中,每个类都是 Object 的子类,因此您不能创建仅包含抽象方法的抽象类。它始终具有从 Object 继承的方法实现:hashCode()equals()toString()

  • 是的,差不多。
  • 例如,在 C++ 中,没有特定的 interface 关键字,接口(interface)只是一个没有实现的类。 C++ 中没有通用基类,因此您确实可以创建一个没有实现的类。

    多重继承并不是真正的决定性特征。 Java具有某种类型的多重继承,具有称为“接口(interface)”的特殊类,甚至可以具有默认方法。

    真正造成差异的是通用基类Objectinterface 是创建不继承自 Object 的类的方式。

    关于java - 没有任何实现和变量的抽象类是有效的接口(interface)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63050082/

    相关文章:

    PHP OOP 模块化 CMS 对象设计

    java - 在窗口关闭时保存组件(JTextField、JTextArea)文本

    python - 你能在Python中得到所有正数吗?

    c# - 将对象转换为正确的类型

    python - 如何在python graphene中处理带参数的查询

    python - 无法使用python从Azure Key Vault获取 secret /证书| 'KeyVaultManagementClient' 对象没有属性 'get_secret'

    php - 多语言网站 - PHP 类 - 正确的做法是什么?

    java - 如何检查Spring Boot应用程序在自动配置类中是否有某个注释

    java - 如何使我的取消按钮功能

    java - 我需要从 JSON 对象中删除特定标签