I know this is possible but whats the use? Since it can only cast the same type as the object being casted?
//then this is declared
Example<Integer> x = new Example<Integer>();
//This is allowed
//this is not allowed, so what's the use?
I see some use in the first one. Since java decides the type on runtime, in this particular case you could declare x like an instance of object, and by downcasting it in that line, you're telling the compiler that x is, indeed, Example.
I think the second one is not allowed in your example because Long is not an subclass of Integer, is more like a brother, since I think both inherit from Number.
Check the docs: Long || Integer
So, if you had done something like:
Example<Number> x = new Example<Number>(); (Example<Integer>) x; (Example<Long>) x;
And then if you dropped your x in something like a visitor, with overloading, your x would've falled inside your
Example<Long> implementation instead of your
Guess I got a little bit confusing in there, but hope it helped.
The quote of the book does not say that you express by example. The book says that you can simply apply the normal rules for casting, as long as the type arguments are the same.
so what's the use?
There are lots of uses.
For example, for casting a wildcard parameter to a specific parameter, or more specific wildcard parameter:
Example<?> x; Example<? extends Number> y; Example<Integer> z; y = (Example<? extends Number>)x; z = (Example<Integer>)x; z = (Example<Integer>)y;
or for casting the actual class to a more specific one:
Example<Integer> x; SubExample<Integer> y; y = (SubExample<Integer>)x;