Hi everyone,
I was wondering, does anyone know if there's a difference between the following two declarations?
Both seem to compile and run fine. But I was wondering, is the 2nd more semantically correct than the 1st?
And what am I trying to do here, I hear you ask? I'm trying to create various types of fruits - Apples, Oranges - that can only compare with themselves. The comparison logic is the same for all fruits, so I'm placing that logic in the superclass
Fruit and using generics to bind compareTo() to the correct subclass. This avoids duplicating the same comparison code in all subclasses. The rest of the code looks like this (compiles and runs correctly):
I'm using the same Apple and Orange definitions for both types of Fruit header declarations.
Since Apple extends Fruit<Apple> and Orange extends Fruit<Orange>, I thought the 2nd Fruit declaration (using <E extends Fruit<E>>
![](https://coderanch.com/images/smilies/8a80c6485cd926be453217d59a84a888.gif)
would be the correct one. However, the code compiles and runs fine with the 1st Fruit declaration too (using <E extends Fruit>
![](https://coderanch.com/images/smilies/8a80c6485cd926be453217d59a84a888.gif)
, so that got me wondering if there really is any difference between the two.
All comments are welcome, cheers!
King
PS. Yes, for those eagle eyes, this is a modified example from Naftalin and Wadler's "Java Generics and Collections", combined with ideas from
Java 5's Enum implementation :-)