← Java from Scratch Lesson 44 of 88 · 10 XP

Interfaces

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

An interface is a list of what a class promises to be able to do:

interface Damageable {
    int getHp();
    void takeDamage(int amount);     // interface methods are public abstract by default
}

interface Healable {
    void heal(int amount);

    default void healFull() {        // a default method: an implementation right in the interface (Java 8+)
        heal(1000);
    }
}

class Player implements Damageable, Healable { … }   // as many interfaces as you like
  • a method that takes a Damageable works with a player, a barrel, a wall — with anything that implements it;
  • checking and casting: if (obj instanceof Healable h) h.heal(10); (Java 16+);
  • an abstract class is "who you are" (one family, with fields), an interface is "what you can do".

Task. Player (HP 100, Damageable and Healable, healing no higher than 100) and Barrel (HP 30, only Damageable). HP doesn't go below 0. Commands hit player 20, heal barrel 10…; if something can't be healed, print cannot.

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