Inheritance and Polymorphism
Inheritance lets one class reuse and extend another's members. A derived class inherits fields and methods from a base class, and can override its behavior.
class Animal
{
public string Name;
public Animal(string name) => Name = name;
public virtual string Speak() => $"{Name} makes a sound.";
}
class Dog : Animal
{
public Dog(string name) : base(name) { }
public override string Speak() => $"{Name} barks.";
}
Animal a = new Dog("Rex");
Console.WriteLine(a.Speak()); // "Rex barks."
The pieces
class Dog : AnimalmeansDoginherits fromAnimal.: base(name)calls the base class's constructor.virtualon a base method marks it as overridable,overrideon the derived method replaces it.- Polymorphism: even though
ais declared asAnimal, callingSpeak()runsDog's version, because the actual object at runtime is aDog. That's why the last line prints "Rex barks." and not "Rex makes a sound."
sealed and base member access
sealed overrideprevents classes that inherit fromDogfrom overridingSpeak()any further.- Inside an overriding method,
base.Speak()calls the base class's original implementation.