Angelika Langer Enum< E延伸Enum< E>>解码 [英] Angelika Langer Enum<E extends Enum<E>> decoding
问题描述
按照我的上一个问题,我正在阅读 Angelika Dissecting Enum 。除了一个类型只能为其子类型实例化并且子类型继承了一些常用方法之外,我无法理解文章。 b
compareTo
方法。当Enum隐式实现 Comparable接口
。为什么需要定义自己的 compareTo
方法?
然而,详细的解释是有用的。
我认为将泛型类型声明为类型< E extends Type< E>>
是这样的泛型类将使子类继承返回或接受具有子类型类型的参数的方法。 java.lang.Enum
中的这些方法是:
public final int compareTo(E o){...}
public final Class< E> getDeclaringClass(){...}
所以,如果我们声明枚举 Color
,隐含的意思是:
public class Color extends Enum< Color>
所以在这个 Enum
的实例中,类型参数 E
被分配了类型参数 Color
,所以上面的方法看起来像这样:
public final int compareTo(Color o){...}
public final Class< Color> getDeclaringClass(){...}
As per my Previous Question, I am reading the article from Angelika Dissecting Enum. Except for the points that a type can only be instantiated for its subtypes and the subtypes do inherit some common methods, I am not able to understand the article.
- What is the meaning of abstract Enum class declared in this way? How is it helpful?
- The document in the last part has described three aspects, can someone explain them in easier terms to me?
- I do see in the code sketch the Enum class is declaring the
compareTo
method. When Enum is implicitly implementingComparable interface
. Why do it needs to define its owncompareTo
method? - Seems like it is a concept of recursive generics. What does recursive generics exactly mean? After doing a bit of R&D and understanding my last question answer, I understand that it forces the class to be parameterized on itself.
Still, a detailed explanation would be useful.
I think the main benefit of declaring generic types as Type<E extends Type<E>>
is that such generic classes will make subclasses to inherit methods which return or accept arguments with subtype's type. Such methods in java.lang.Enum
are:
public final int compareTo( E o) { ... }
public final Class< E > getDeclaringClass() { ... }
So, if we declare the enum Color
, that implicitly means:
public class Color extends Enum<Color>
so in this instantiation of Enum
the type paramater E
is assigned the type argument Color
, so the above methods will look like these:
public final int compareTo(Color o) { ... }
public final Class<Color> getDeclaringClass() { ... }
这篇关于Angelika Langer Enum< E延伸Enum< E>>解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!