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 instantiatedsealed— cannot be further inherited
Your Task
Create:
- A base class
Shapewith avirtual double Area()method returning0 - A
Squaresubclass with aSideproperty that overridesArea()to return side² - A
Circlesubclass with aRadiusproperty that overridesArea()to return π × radius²
WasmSharp (.NET) loading...
Loading...
Click "Run" to execute your code.