Java Oddity: How an upcast can save the day

You almost never see an upcast in Java code. That is, you rarely see something like this:

…((Animal) someDog)…

Why would you need to? The fact that a Dog is an Animal should be apparent for the compiler!

Here is however a program that fails to compile without an upcast:

class Player {

    private boolean isAlive = true;

    // ...

    void kill(Opponent opponent) {

        // Does not compile
        opponent.isAlive'isAlive' has private access in 'Player' = false;




        // Does compile
        ((Player) opponent).isAlive = false;
    }

    // ...
}

class Opponent extends Player {
    // ...
}

Comments

Be the first to comment!