Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why `T extends String` is allowed but gives warning? [duplicate]

Tags:

java

generics

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.

like image 327
Amit Deshpande Avatar asked Sep 18 '12 10:09

Amit Deshpande


2 Answers

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.

like image 152
axtavt Avatar answered Oct 20 '22 18:10

axtavt


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:

  • The case where SomeFinalClass originally was not final.
  • The case where the code for Car is generated automatically, and it would be awkward to generate special-case code for final classes.
like image 44
Stephen C Avatar answered Oct 20 '22 18:10

Stephen C