Lesson 13 of 15

Inheritance

Inheritance

Inheritance lets a class extend another, reusing and overriding behavior:

class Animal {
    public string Name { get; set; }
    public Animal(string name) { Name = name; }
    public virtual string Sound() => "...";  // virtual = overridable
    public string Describe() => $"{Name} says {Sound()}";
}

class Dog : Animal {
    public Dog(string name) : base(name) {}        // call parent constructor
    public override string Sound() => "Woof";      // override parent method
}

class Cat : Animal {
    public Cat(string name) : base(name) {}
    public override string Sound() => "Meow";
}

var animals = new Animal[] { new Dog("Rex"), new Cat("Luna") };
foreach (var a in animals) {
    Console.WriteLine(a.Describe());
}
// Rex says Woof
// Luna says Meow

sealed and abstract

  • abstract — must be overridden; the class cannot be instantiated
  • sealed — cannot be further inherited

Your Task

Create:

  • A base class Shape with a virtual double Area() method returning 0
  • A Square subclass with a Side property that overrides Area() to return side²
  • A Circle subclass with a Radius property that overrides Area() to return π × radius²
WasmSharp (.NET) loading...
Loading...
Click "Run" to execute your code.