Lesson 9 of 10
Inheritance and interfaces
- 16 min
- 5 checks
- 3 hints
- Go to task
Goal
The abstract, override and interface keywords
Explanation
Inheritance builds one class on top of another: class Goblin : Enemy inherits all the properties and methods in Enemy, and its constructor passes data to the parent class's constructor with : base("Goblin", 30). Writing abstract class Enemy makes Enemy an abstract class: it represents a general idea and can't be instantiated directly, so new Enemy(...) is a compile error: the game has no "enemy" without a kind, only goblins and knights.
An abstract method has no body, and every child class must write it with override. A virtual method has a ready-made body, and a child class may replace it with override and can still call the parent's version with base.TakeDamage(...). This is where polymorphism comes in: a List<Enemy> holds goblins and knights together, and e.Attack() calls each one's own version at run time. Watch out, though: writing a method with the same name without override hides the parent's method instead of replacing it, so a reference of type Enemy still reaches the parent's version, and all the compiler gives you is a warning.
An interface lists the methods a class must have without implementing them, as in interface IDamageable { void TakeDamage(int amount); }. Every class that writes : IDamageable must implement its methods and make them public, even if it shares no parent with the other classes. That's how a bullet in Unity can hit anything it touches, whether it's an enemy or a barrel, without knowing its type. A class inherits from only one parent, but it can implement any number of interfaces.
Your task
Make Enemy an abstract class, with Attack() as an abstract method and TakeDamage as a virtual one. Then write Attack() with override in Goblin to return 5 and in Knight to return 12, and make the armored knight take only half the damage by overriding TakeDamage. Make Barrel implement IDamageable so that any hit breaks it and sets Broken to true, then complete TotalAttack(enemies) to add up the attacks of the living enemies only.
Checks
5 checks- Enemy is an abstract class, and its Attack method is abstract too
- Through an Enemy reference, each enemy attacks with its own strength: 5 for the goblin and 12 for the knight
- Through an Enemy reference, the knight takes half the damage and the goblin takes all of it
- Barrel implements IDamageable, and any hit breaks it
- TotalAttack adds up the attacks of the living only