Can anyone help me understanding type assigning and erasure in the following code, and why only line24 throws class cast exception not line21. Its a continuation of previous post, which I cud not follow much.
SCJP 1.6, SCWCD 5.0, SCBCD 5.0 [loading..]
Harshit Rastogi
Ranch Hand
Joined: Apr 15, 2008
Posts: 131
posted
0
you can follow this link where discussion on same doubt is going :Generic type casting
I have already been to that post. This post infact is because of the one you pointed to me.
I needed a simpler explanation and hence posted relatively a simple example.
I am still waiting for a better explanation from someone.
Ruben Soto
Ranch Hand
Joined: Dec 16, 2008
Posts: 1032
posted
0
Because when you concatenate two String objects, the compiler avoids calling toString() on the second object and performs some code specific to String + String concatenation, so in that case a cast to String (which will fail in this case) is performed. But for all other types toString() is called on the second object, and since toString() is defined in Object, the compiler doesn't bother with the casting to String, and simply casts to Object, which will succeed (since all objects are instances of Object.)
All code in my posts, unless a source is explicitly mentioned, is my own.
Himalay Majumdar
Ranch Hand
Joined: Sep 28, 2008
Posts: 324
posted
0
Hi Ruben..can you please tell how the code will look after type erasure.
Ruben Soto
Ranch Hand
Joined: Dec 16, 2008
Posts: 1032
posted
0
Himalay Majumdar wrote:Hi Ruben..can you please tell how the code will look after type erasure.
Hi Himalay,
It will look something like this:
Himalay Majumdar
Ranch Hand
Joined: Sep 28, 2008
Posts: 324
posted
0
I knew you tried explaining the String behaviour before..which i cud not follow.
Can you please explain me why only cast to String is performed in Line 11 of your code.
I dont see any concatenation(apart from the plus sign) here..
System.out.println("1) " + (String) box2.u);
i mean System.out.println(box2.u); produces the same error.
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.