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) {

((Player) opponent ) . isAlive = false ;

}

}



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 .