C# inheritance, virtual, and abstract members

A subclass inherits the members of its base class. A base member marked virtual can be replaced in a subclass with override, and an abstract member has no body and must be overridden. When code calls the member through a base-type variable, the version of the actual object runs. This is polymorphism: the same call behaves differently for different objects.

C#
using System;

abstract class Employee {
  public string Name { get; }

  protected Employee(string name) {
    Name = name;
  }

  public abstract int MonthlyPay();

  public virtual string Title {
    get { return "Employee"; }
  }

  public override string ToString() {
    return Title + " " + Name + ": " + MonthlyPay();
  }
}

class Salaried : Employee {
  private readonly int yearly;

  public Salaried(string name, int yearly) : base(name) {
    this.yearly = yearly;
  }

  public override int MonthlyPay() {
    return yearly / 12;
  }
}

class Hourly : Employee {
  private readonly int rate;
  private readonly int hours;

  public Hourly(string name, int rate, int hours) : base(name) {
    this.rate = rate;
    this.hours = hours;
  }

  public override int MonthlyPay() {
    return rate * hours;
  }
}

sealed class Manager : Salaried {
  private readonly int bonus;

  public Manager(string name, int yearly, int bonus) : base(name, yearly) {
    this.bonus = bonus;
  }

  public override string Title {
    get { return "Manager"; }
  }

  public override int MonthlyPay() {
    return base.MonthlyPay() + bonus;
  }
}

class Program {
  static void Main() {
    Employee[] staff = {
      new Salaried("Ada", 60000),
      new Hourly("Bo", 20, 160),
      new Manager("Cy", 96000, 500),
    };
    int total = 0;
    foreach (Employee e in staff) {
      Console.WriteLine(e);
      total += e.MonthlyPay();
    }
    Console.WriteLine("total " + total);
  }
}
Read the full lesson