LearnFrenzy
Sign in Take a free test

Inheritance · Inheritance Programs · Question 9

Game characters with shared base stats in Java Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

Write a GameCharacter base class (name, health, attack) with Warrior (armour reduces damage) and Healer (heals itself every other turn) subclasses; simulate a fight until one falls.

Solution
Main.java
class GameCharacter {
    protected final String name;
    protected int health;
    protected final int attack;

    GameCharacter(String name, int health, int attack) { this.name = name; this.health = health; this.attack = attack; }

    void receive(int damage) { health = Math.max(0, health - damage); }
    void onTurn(int turn) { }
    boolean alive() { return health > 0; }
    @Override public String toString() { return name + "(" + health + ")"; }
}

class Warrior extends GameCharacter {
    private final int armour;
    Warrior(String n) { super(n, 120, 14); armour = 4; }
    @Override void receive(int damage) { super.receive(Math.max(1, damage - armour)); }
}

class Healer extends GameCharacter {
    Healer(String n) { super(n, 90, 11); }
    @Override void onTurn(int turn) { if (turn % 2 == 0) health = Math.min(90, health + 12); }
}

public class Main {
    public static void main(String[] args) {
        GameCharacter w = new Warrior("Bheem"), h = new Healer("Dhanvantari");
        int turn = 0;
        while (w.alive() && h.alive()) {
            turn++;
            w.onTurn(turn); h.onTurn(turn);
            h.receive(w.attack);
            if (h.alive()) w.receive(h.attack);
            if (turn % 3 == 0) System.out.println("turn " + turn + ": " + w + " " + h);
        }
        System.out.println("turn " + turn + ": " + (w.alive() ? w.name : h.name) + " wins with " + (w.alive() ? w.health : h.health) + " HP");
    }
}

Output Verified by compiling and running

turn 3: Bheem(99) Dhanvantari(60)
turn 6: Bheem(78) Dhanvantari(42)
turn 9: Bheem(57) Dhanvantari(12)
turn 11: Bheem wins with 50 HP

Warrior refines receive() and calls super.receive() with reduced damage; Healer refines the onTurn() hook. The loop only uses GameCharacter methods.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links