← C# from Scratch
Lesson 34 of 39 · 10 XP
Abstraction
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
An abstract class is an "unfinished" blueprint: you can't create an object from it, only from its subclasses. An abstract method has no body; every subclass must implement (override) it:
abstract class Enemy
{
public string Name { get; }
protected Enemy(string name) { Name = name; }
public abstract int Damage(); // the what is known; the how is up to the subclass
public void Attack() => // an ordinary method is allowed too
Console.WriteLine($"{Name} hits for {Damage()}");
}
class Orc : Enemy
{
public Orc() : base("Orc") { }
public override int Damage() => 12;
}
new Enemy("?"); // error CS0144: cannot create an instance of the abstract class
Forget override Damage() in a subclass and you get compile error CS0534. This way the compiler makes sure no
kind of enemy is left "without an attack".
Task. Finish the subclasses of the abstract Employee: Manager (salary = base salary + 20 %) and
Intern (salary = half the base salary). The program prints the salaries and the total payroll.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.