override(C# 참조)

override 한정자는 상속된 메서드, 속성, 인덱서 또는 이벤트의 추상 또는 가상 구현을 확장하거나 수정하는 데 필요합니다.

다음 예제에서 Square 클래스는 GetArea가 추상 Shape 클래스에서 상속되기 때문에 GetArea의 재정의된 구현을 제공해야 합니다.

abstract class Shape
{
    public abstract int GetArea();
}

class Square : Shape
{
    private int _side;

    public Square(int n) => _side = n;

    // GetArea method is required to avoid a compile-time error.
    public override int GetArea() => _side * _side;

    static void Main()
    {
        var sq = new Square(12);
        Console.WriteLine($"Area of the square = {sq.GetArea()}");
    }
}
// Output: Area of the square = 144

override 메서드는 기본 클래스에서 상속된 멤버의 새 구현을 제공합니다. override 선언에서 재정의된 메서드를 재정의된 기본 메서드라고 합니다. override 메서드에는 재정의된 기본 메서드와 동일한 시그니처가 있어야 합니다. override 메서드는 공변 반환 형식을 지원합니다. 특히 override 메서드의 반환 형식은 해당하는 기본 메서드의 반환 형식에서 파생될 수 있습니다.

비가상 또는 정적 메서드는 재정의할 수 없습니다. 재정의된 기본 메서드는 virtual, abstract 또는 override여야 합니다.

override 선언에서는 virtual 메서드의 액세스 가능성을 변경할 수 없습니다. override 메서드 및 virtual 메서드 둘 다에 동일한 액세스 수준 한정자가 있어야 합니다.

new, static 또는 virtual 한정자를 사용하여 override 메서드를 수정할 수 없습니다.

재정의 속성 선언은 상속된 속성과 동일한 액세스 한정자, 형식 및 이름을 지정해야 합니다. 읽기 전용 재정의 속성은 공변 반환 형식을 지원합니다. 재정의된 속성은 virtual, abstract 또는 override여야 합니다.

override 키워드 사용 방법에 대한 자세한 내용은 Override 및 New 키워드를 사용하여 버전 관리Override 및 New 키워드를 사용해야 하는 경우를 참조하세요. 상속에 대한 자세한 내용은 상속을 참조하세요.

예제

이 예제에서는 Employee라는 기본 클래스와 SalesEmployee라는 파생 클래스를 정의합니다. SalesEmployee 클래스에는 추가 필드 salesbonus가 포함되어 있고, 이를 고려하기 위해 CalculatePay 메서드를 재정의합니다.

class TestOverride
{
    public class Employee
    {
        public string Name { get; }

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

        // Constructor to set the name and basepay values.
        public Employee(string name, decimal basepay)
        {
            Name = name;
            _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)
        {
            _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.
        var employee1 = new SalesEmployee("Alice", 1000, 500);
        var employee2 = new Employee("Bob", 1200);

        Console.WriteLine($"Employee1 {employee1.Name} earned: {employee1.CalculatePay()}");
        Console.WriteLine($"Employee2 {employee2.Name} earned: {employee2.CalculatePay()}");
    }
}
/*
    Output:
    Employee1 Alice earned: 1500
    Employee2 Bob earned: 1200
*/

C# 언어 사양

자세한 내용은 C# 언어 사양재정의 메서드 섹션을 참조하세요.

공변 반환 형식에 대한 자세한 내용은 기능 제안 노트를 참조하세요.

참고 항목