Lesson 9 of 10
Inheritance and polymorphism
- 15 min
- 6 checks
- 3 hints
- Go to task
Goal
The abstract and super keywords and the @Override annotation
Explanation
A child class inherits from another class with the extends keyword: it gets the parent's fields and methods, then adds to them or changes some of them. class Skeleton extends Enemy means a skeleton is an enemy, so any code that accepts an Enemy accepts it too. The child's constructor starts by calling the parent's constructor like this: super("Skeleton", 16);.
An abstract class, marked abstract, can't be used to create objects directly. It has methods with no body, like public abstract int attack();, and every child class must define them, or the compiler rejects the code. A close relative is the interface, a list of methods that a class promises to define. It has no instance fields, and a class takes it on with the implements keyword. A class can inherit from only one parent, but it can implement any number of interfaces.
When a child defines a method with the same signature as one in the parent, it overrides it. You write @Override before it, and you can build on the parent's version instead of repeating it, as in super.takeHit(damage / 2). That's where polymorphism comes from: in for (Enemy e : wave), e.attack() calls the version from each object's real class, not the Enemy version.
Your task
Complete Skeleton so its name is Skeleton, its health is 16 and its attack is 5. Complete Golem so its name is Golem, its health is 100 and its attack is 12, and have it override takeHit so it only takes half the damage. Then write totalAttack(wave) to return the wave's total attack, and survivors(wave, damage) to hit every enemy with damage and return how many are still alive. Finally, print one line per enemy from main in the form Zombie: 3, followed by the line Wave damage: 20.
Checks
6 checks- Skeleton has the right name, 16 health and 5 attack
- Golem has the right name, 100 health and 12 attack
- Golem takes half of a hit, and other enemies take all of it
- totalAttack adds up each enemy's own attack
- survivors hits the whole wave and counts the ones still alive
- One line per enemy was printed, then the wave damage