Java Reference
In-Depth Information
common supertype:
return rnd.nextBoolean() ?
(CoinSide)Heads.INSTANCE : Tails.INSTANCE;
In release 5.0 and later releases, the language is much more forgiving. The conditional operator is
always legal when its second and third operands have reference types. The result type is the least
common supertype of these two types. A common supertype always exists, because Object is the
supertype of every object type. As a practical matter, the main consequence of this change is that
the conditional operator just does the right thing more often and gives compile-time errors less
often. For the language nerds among us, the compile-time type of the result of the conditional
operator for reference types is the same as the result of invoking the following method on the
second and third operands [JLS 15.25]:
<T> T choose(T a, T b) { }
The problem illustrated by this puzzle did come up fairly often under release 1.4 and earlier
releases, forcing you to insert casts that served merely to obscure the purpose of your code. That
said, the puzzle itself is artificial. Before release 5.0, it would have been more natural to write
CoinSide using the Typesafe Enum pattern [EJ Item 21]:
import java.util.Random;
public class CoinSide {
public static final CoinSide HEADS = new CoinSide("heads");
public static final CoinSide TAILS = new CoinSide("tails");
private final String name;
private CoinSide(String name) {
this.name = name;
}
 
 
Search WWH ::




Custom Search