← C# from Scratch Lesson 32 of 39 · 10 XP

Inheritance

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A subclass gets the parent's fields and methods and adds its own:

class Animal
{
    public string Name { get; }
    public Animal(string name) { Name = name; }
    public void Eat() => Console.WriteLine($"{Name} is eating");
}

class Dog : Animal                         // Dog inherits from Animal
{
    public Dog(string name) : base(name) { }   // base(...) is the parent's constructor
    public void Bark() => Console.WriteLine($"{Name}: Woof!");
}

var d = new Dog("Sharik");
d.Eat();     // from Animal
d.Bark();    // its own
Animal a = d;   // a subclass object can be put into a variable of the parent type
  • a class has one parent (C# has no multiple inheritance of classes — that's what interfaces are for);
  • protected members are visible to subclasses, private ones aren't;
  • sealed class forbids inheriting any further.

Task. There's a Character class (name, HP). Finish Warrior : Character with an armour property Armor and a method TakeHit(int dmg): the damage is reduced by the armour, but not below 1. The program creates a warrior and hits him.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.