方法覆写

(重定向自方法覆盖

面向对象的编程中,方法覆写是一种语言功能,它允许子类或子类提供已由其超类或父类之一提供的方法的特定实现。 它允许特定类型的多态性(子类型)。 子类中的实现通过提供与父类中的方法具有相同名称、相同参数或签名以及相同返回类型的方法来覆盖(替换)超类中的实现。[1]执行的方法的版本将由用于调用它的对象确定。 如果使用父类的对象调用方法,则执行父类中的版本,如果使用子类的对象调用方法,则执行子类中的版本。 [2] 某些语言允许程序员防止方法被覆盖。

Illustration

名称 编辑

部分编程语言的英文术语会区分 “overwrite” 和 “override” 两个词。在 C++ 的术语中,override 指的是以具有相同名称及参数列的函数覆盖其父类中的虚拟函数,overwrite 则是指以名称相同但参数列不同的函数覆盖其父类中的虚拟函数或以名称相同且参数列相同的函数覆盖其父类中的非虚拟函数。[3][4]然而这两个词都经常被翻译为中文的“覆写[5],故而导致混淆。

特定语言示例 编辑

Ada 编辑

Ada 默认提供方法覆盖。为了有利于早期错误检测(例如拼写错误),可以指定何时期望方法实际覆盖或不覆盖。这将由编译器检查。

  type T is new Controlled with ......;
  procedure Op(Obj: in out T; Data: in Integer);

  type NT is new T with null record;
  overriding    -- overriding indicator
  procedure Op(Obj: in out NT; Data: in Integer);
  overriding    -- overriding indicator
  procedure Op(Obj: in out NT; Data: in String);
  -- ^ compiler issues an error: subprogram "Op" is not overriding

C# 编辑

C# 确实支持方法覆盖,但仅在使用修饰符overridevirtualabstract明确要求时。

abstract class Animal
{
    public          string Name { get; set; }
    // Methods
    public          void   Drink();
    public virtual  void   Eat();
    public          void   Go();
}

class Cat : Animal
{
    public new      string Name { get; set; }
    // Methods
    public          void   Drink();  // Warning: hides inherited drink(). Use new
    public override void   Eat();    // Overrides inherited eat().
    public new      void   Go();     // Hides inherited go().
}

注释 编辑

  1. ^ Flanagan 2002, p. 107
  2. ^ Lewis & Loftus 2006, p.454
  3. ^ C++中的Overload、Override和Overwrite – 煎炸熊の記事本. note.artchiu.org. [2023-12-30]. (原始内容存档于2023-12-30). 
  4. ^ Override Overload Overwrite. wuciawe.github.io. [2023-12-30]. (原始内容存档于2023-12-30). 
  5. ^ Lee, Wayne. Override(覆寫) & Overload(多載) &Polymorphism(多型)的差異. Medium. 2020-07-26 [2023-12-30]. (原始内容存档于2023-12-30) (英语). 

参考文献 编辑

页面存档备份,存于互联网档案馆