And yet it works great!
public static <E extends Number> void A() { E x = (E)new Double(2.2); }
Be kind to your compiler, and it will be good for you. All you have to do is say what you mean.
And, of course, since we are actually lying to our compiler, this allows us to do scary things like:
public class Test { public static <E extends Number> E makeOne() { E x = (E) new Double(2.2); return x; }
For our readers at home ... this is not how generics should be used.
Oh - and by the way, the reason you see your problem is because you don't match types without casting.
Your problem is conceptual. The type passed in the Generic <E extends Number> expression is not a place holder for the type that you finally decided to use. You do not just put off your decision about which type to use. You promise to use only those types that match this sentence, and if you ever break that promise, the compiler should warn you.
The reason your code is not accepted is because you are doing exactly that, you are breaking that promise. You say that although the caller can use any Number , you will use a specific Number ( Double ) to break the rules that you yourself set, and the compiler says you disconnected.
source share