方法覆写

维基百科,自由的百科全书
Illustration

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

特定语言示例[编辑]

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# 确实支持方法覆盖,但仅在使用修饰符 Template:C sharpTemplate:C sharpTemplate:C sharp明确要求时。

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

参考文献[编辑]