Abstract Methods.
The entire point of the abstract class is to be subclassed and have different subclasses define the missing methods, relying on dynamic dispatch for the code in the superclass to call the code in the subclass. (abstract method)
抽象类是纯粹用于继承的类。我们常常能见到其定义了一些方法,这些方法中又调用了类中未定义的方法。如果我们尝试实例化抽象类并调用相应的方法,method missing 错误将会发生。
1 | class Doubler |
仔细想想,抽象类起到的作用实际上与 mixins 是一致的。它们定义的方法常常会调用其他未定义的方法,而这些 “missing methods” 留待其子类 (或 include 该 mixin 的类) 进行实现。我们把这些在子类中实现的方法称为 abstract methods。
如上例,Doubler 类是一个 abstract class,而 + 方法是 abstract method。注意,double 方法是有“意义”的方法;在被子类继承后,若子类提供了 abstract method (即 + 方法) 的实现,那么通过 dynamic dispatch,double 方法的代码将能够调用子类实现的 abstract method。
在 statically typed languages 中,这一问题更加有趣。由于 type checker 将会在 compile-time 探测并阻止 method missing 错误的产生,我们需要以某种方式提前声明相应的方法为 abstract method,使其能够通过 type checker 的检测。
在 C++ 中,声明 abstract method 的方式是在抽象类中定义缺少实现的空函数,并添加 virtual 关键字;因此 abstract method 又被称为 pure virtual method (纯虚函数)。引入抽象类与抽象方法的概念后,静态类型语言能够更好的支持抽象类与其相关的 features。
- Thanks to subtyping in these languages, we can have expressions with the type of the superclass and know that at run-time the object will actually be one of the subclasses.
- Type-checking ensures the object’ class has implemented all the abstract methods, so it is safe to call such methods.
OOP 中的 abstract methods 与 FP 中的 higher-order functions 之间存在微妙的联系:They both support a programming pattern where some code is passed other code in a flexible and reusable way.
- 在 OOP 中,不同的子类以不同的方式实现抽象方法;父类中的代码可以通过 dynamic dispatch 调用子类中的不同实现。即子类中的抽象方法实现传入父类的代码中。
- 在 FP 中,higher-order functions 能够以函数作为参数,不同的 callers 能够提供不同的函数实现。即 callers 的实参函数实现传入 higher-order function 的函数体代码中。
另外,支持 abstract method 与 multiple inheritance 的语言 (例如 C++) 并不需要 interface。一个只定义 abstract method (i.e., pure virtual method) 的抽象类起到的作用与 interface 一致。
Reference
Supplementry notes:
Course info:
Programming Languages, Part C, University of Washington, Lecturer: Professor Dan Grossman.