← Java from Scratch Lesson 37 of 88 · 10 XP

Encapsulation

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Fields are private, and access goes through getters and setters, where the rules live:

class Player {
    private int hp = 100;
    private final int maxHp = 100;

    public int getHp() { return hp; }

    public void setHp(int hp) {
        this.hp = Math.max(0, Math.min(maxHp, hp));   // can't go below zero or above the maximum
    }

    public boolean isDead() { return hp == 0; }       // a boolean getter starts with is
}

What for: the rule "HP from 0 to 100" is written in one place. From the outside you can't accidentally set hp = -500, and the inner workings of the class can be changed without breaking the code that uses it.

Task. BankAccount with a private balance: deposit(int) (positive amounts only), boolean withdraw(int) (not more than the balance, and not ≤ 0), getBalance(). Commands dep N, wd N; for each withdrawal print ok / denied, and at the end the balance.

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