Lesson 9 of 10

Inheritance and polymorphism

Goal

The abstract and super keywords and the @Override annotation

01

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.

02

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
  1. Skeleton has the right name, 16 health and 5 attack
  2. Golem has the right name, 100 health and 12 attack
  3. Golem takes half of a hit, and other enemies take all of it
  4. totalAttack adds up each enemy's own attack
  5. survivors hits the whole wave and counts the ones still alive
  6. One line per enemy was printed, then the wave damage
03

Hints

0/3
Track lessons0 of 10 done

Java is the language behind Android apps and large systems. Everything in it lives inside a class, and you state every variable's type explicitly.

Beginner level, 10 lessons, 2 hours in total.

Main.java
OutputJava 13 (Judge0)

Compiling and running your code on the server.

–/6

Compiling and running your code on the server.

6 checks listed under “Your task”.

Track lessons0 of 10 done

Java is the language behind Android apps and large systems. Everything in it lives inside a class, and you state every variable's type explicitly.

Beginner level, 10 lessons, 2 hours in total.