Inheritance
A class inherits from another using : BaseClass, automatically getting access to its fields and methods. base(name) inside a subclass's constructor calls the parent class's constructor, which is required before the subclass constructor can do anything else when the parent has no parameterless constructor.
A method has to be explicitly marked virtual in the base class before a subclass can override it with override — unlike Java, where every method is overridable unless marked final.
using System;
class Animal {
public string Name;
public Animal(string name) { Name = name; }
public virtual string Speak() {
return Name + " makes a sound";
}
}
class Cat : Animal {
public Cat(string name) : base(name) { }
public override string Speak() {
return Name + " meows";
}
}
class Program {
static void Main() {
Cat cat = new Cat("Whiskers");
Console.WriteLine(cat.Speak());
}
}Whiskers meows
Next: interfaces — describing shared behavior across otherwise-unrelated classes.
Practice exercise
Define a class Animal with a field Name and a virtual method Speak() returning Name + " makes a sound". Define a class Cat that extends Animal and overrides Speak() to return Name + " meows". Create a Cat named "Whiskers" and print its Speak().