public abstract class Enum<E extends Enum<E>>Why is the type parameter declared as
<E extends Enum<E>>? What would happen if it were declared as <E extends Enum> instead?Solution
This pattern is used when a generic base class needs to reference the type of the subclass. For example, suppose we had:
public enum CardSuit { HEARTS, CLUBS, DIAMONDS, SPADES }This gets compiled as something like:
public class CardSuit extends Enum<CardSuit>....which then means that every occurrence of type parameter E in Enum's declaration becomes CardSuit. Thus, the superclass (Enum) is able to reference subclass types in its method signatures and return types this way through the type parameter.
If just
<E extends Enum> were used instead, that would still be the case, but some information would be lost. The type parameter E is mentioned in three places in Enum:- implements Comparable<E>
- public int compareTo(E o)
- public Class<E> getDeclaringClass()
E extends Enum, then the Comparable interface is only aware of Comparable<Enum> instead of Comparable<CardSuit>. So E extends Enum<E> contains some extra information, making it more typesafe.
No comments:
Post a Comment