Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
621 views
in Technique[技术] by (71.8m points)

generics - What would be different in Java if Enum declaration didn't have the recursive part

Please see Java Enum definition and Why in java enum is declared as Enum<E extends Enum<E>> for general discussion. Here I would like to learn what exactly would be broken (not typesafe anymore, or requiring additional casts etc) if Enum class was defined as

public class Enum<E extends Enum> 

I'm using this code for testing my ideas:

interface MyComparable<T> {
    int myCompare(T o);
}

class MyEnum<E extends MyEnum> implements MyComparable<E> {
    public int myCompare(E o) { return -1; }
}

class FirstEnum extends MyEnum<FirstEnum> {}

class SecondEnum extends MyEnum<SecondEnum> {}

With it I wasn't able to find any benefits in this exact case.

PS. the fact that I'm not allowed to do

class ThirdEnum extends MyEnum<SecondEnum> {}

when MyEnum is defined with recursion is
a) not relevant, because with real enums you are not allowed to do that just because you can't extend enum yourself
b) not true - pls try it in a compiler and see that it in fact is able to compile w/o any errors

PPS. I'm more and more inclined to believe that the correct answer here would be "nothing would change if you remove the recursive part" - but I just can't believe that.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, first of all it would complain about using the raw type, but you could do:

public class Enum<E extends Enum<?>>

for the same effect.

Also, with this type of generic you could do something like:

class FirstEnum extends MyEnum<SecondEnum> {
}

class SecondEnum extends MyEnum<FirstEnum> {
}

which to me seems like it could lead to a lot of trouble. More exactly you can't compare an enum of type FirstEnum with an enum of the same type, you have to compare it with an enum of the other type, which is really troublesome if you have a List<FirstEnum> that you want sorted. The example will not compile if i set E instead o ? since SecondEnum is not of the type E extends MyEnum<E> (this would lead to circular inheritance). It will work if FirstEnum extends MyEnum<FirstEnum> though (which would mean that SecondEnum is a child class of FirstEnum - normal hierarchical inheritance).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...