Possible Duplicate:
@SuppressWarnings for “extends String”
Why T extends String
is allowed but gives warning?
The type parameter T should not be bounded by the final type String. Final types cannot be further extended
public class Car<T extends String>
I Know what is final I know It is valid because only possible value of T can be String
I was wondering about Warning.
If the actual question is "why it's allowed", then imagine a situation when you add final
keyword to existing class. I think you don't want this change to break other exisisting code that uses this class as a generic bound, because it's still perfectly legal. That's why compiler does not emit an error in this case.
From the other side, you want to be informed if you accidentially use final
class as a generic bound, because such a constuct doesn't make sense. That's why compiler emits a warning.
Actually, it's a common practice to mark legal but meaningless constructs with warnings.
Basically, it is saying that there is only one possible type for T
and that is String
itself. So basically your generic Car
class is generic only in name. You may as well just replace all instances of T
in the class with String
.
Perhaps you mean public class Car<T extends CharSequence>
...
The construct is allowed because the class is meaningful, and possibly even useful. The warning is given because (in the opinion of the compiler writers) you have probably made a mistake. The reasoning is the same as for the warning that some compilers will give you for the following:
String NULL = null;
System.err.println(NULL.toString());
This is meaningful, but it is a mistake ... unless you intend it to throw an exception.
I can think of two scenarios where public class Car<T extends SomeFinalClass>
is not a mistake:
SomeFinalClass
originally was not final
.Car
is generated automatically, and it would be awkward to generate special-case code for final
classes.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With