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 evident to the compiler!

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

class Player {
    private boolean isAlive = true;

    void kill(Opponent opponent) {
        // Compiles
        // Error: 'isAlive' has private access in 'Player'
       
 ((Player)
 opponent
)
.isAlive = false;

        // opponent.opponentSpecificMethod();
    }
}

class Opponent extends Player {
    // ...
}

Note: The snippet above is written to illustrate a language oddity and should not be seen as an example of good design. In fact, the need for an upcast is a telltale of a bad design. In particular a base class should not be coupled to one of its subclasses the way Player is coupled to Opponent.

Comments (2)

User avatar

Private members cannot be accessed by child classes. You want protected access.

by holothuroid |  Reply
User avatar

No one is accessing isAlive from a child class here. The field is used only in Player, and thus anything but private would be an unncessary sacrifice of encapsulation.

by Andreas Lundblad |  Reply

Add comment