override

要擴展或修改繼承的方法、屬性、索引器或事件的抽象實現或虛實現,必須使用 override 修飾符。javascript

在此例中,類 Square 必須提供 Area 的重寫實現,由於 Area 是從抽象的 ShapesClass 繼承而來的。html

abstract class ShapesClass
{
    abstract public int Area();
}

class Square : ShapesClass
{
    int x, y;
    // Because ShapesClass.Area is abstract, failing to override
    // the Area method would result in a compilation error.
    public override int Area()
    {
        return x * y;
    }
}

有關 override 關鍵字用法的更多信息,請參見使用 Override 和 New 關鍵字進行版本控制以及瞭解什麼時候使用 Override 和 New 關鍵字java

備註

override 方法提供從基類繼承的成員的新實現。經過 override 聲明重寫的方法稱爲重寫基方法。重寫的基方法必須與 override 方法具備相同的簽名。有關繼承的信息,請參見繼承ide

不能重寫非虛方法或靜態方法。重寫的基方法必須是 virtualabstractoverride 的。this

override 聲明不能更改 virtual 方法的可訪問性。override 方法和 virtual 方法必須具備相同的訪問級別修飾符spa

不能使用修飾符 newstaticvirtualabstract 來修改 override 方法。版本控制

重寫屬性聲明必須指定與繼承屬性徹底相同的訪問修飾符、類型和名稱,而且被重寫的屬性必須是 virtualabstractoverride 的。code

示例

此示例定義了一個名爲 Employee 的基類,和一個名爲 SalesEmployee 的派生類。SalesEmployee 類包括一個額外的屬性 salesbonus,並重寫方法 CalculatePay 以便將該屬性考慮在內。xml

using System;
class TestOverride
{
    public class Employee
    {
        public string name;

        // Basepay is defined as protected, so that it may be 
        // accessed only by this class and derrived classes.
        protected decimal basepay;

        // Constructor to set the name and basepay values.
        public Employee(string name, decimal basepay)
        {
            this.name = name;
            this.basepay = basepay;
        }

        // Declared virtual so it can be overridden.
        public virtual decimal CalculatePay()
        {
            return basepay;
        }
    }

    // Derive a new class from Employee.
    public class SalesEmployee : Employee
    {
        // New field that will affect the base pay.
        private decimal salesbonus;

        // The constructor calls the base-class version, and
        // initializes the salesbonus field.
        public SalesEmployee(string name, decimal basepay, 
                  decimal salesbonus) : base(name, basepay)
        {
            this.salesbonus = salesbonus;
        }

        // Override the CalculatePay method 
        // to take bonus into account.
        public override decimal CalculatePay()
        {
            return basepay + salesbonus;
        }
    }

    static void Main()
    {
        // Create some new employees.
        SalesEmployee employee1 = new SalesEmployee("Alice", 
                      1000, 500);
        Employee employee2 = new Employee("Bob", 1200);

        Console.WriteLine("Employee " + employee1.name + 
                  " earned: " + employee1.CalculatePay());
        Console.WriteLine("Employee " + employee2.name + 
                  " earned: " + employee2.CalculatePay());
    }
}

輸出

Employee Alice earned: 1500
Employee Bob earned: 1200
相關文章
相關標籤/搜索