| Author |
Casting a Reference
|
Deepali Pate
Ranch Hand
Joined: Mar 20, 2002
Posts: 114
|
|
Can someone explain with an example the theroy hidden in this statement. In contrast to converting and casting primitives, converting and casting a reference to a variable does not change the object being referred to. Once created, an object can be referred to in a variety of ways, but the object type is not changed. You will find this in the TIP on page 105 of Java2 Exam Cram by Bill Brogden Thx
|
 |
Jessica Sant
Sheriff
Joined: Oct 17, 2001
Posts: 4313
|
|
I'll take a crack at it... Notice no matter what object I cast it too -- the reference to the variable itself does not change. the object type is unchanged as well.
|
 |
Corey McGlone
Ranch Hand
Joined: Dec 20, 2001
Posts: 3271
|
|
Jess is definitely on the right track. It might also help to look at the class of an object before and after casting. Think about casting primitives: In order to evaluate this expression, the JVM take the value i, which is: 00000000 00000000 00010011 10001000 = 5000 and turns it into this: 10001000 = -120 As you can see, the actual value is modified in order to be placed into the byte variable. However, if you cast a reference variable, the object that it is referred to is not modified in any way. You may now treat it differently, but the object remains unchanged. Take a look at this code: You can see that, even though I cast the object 3 times, the type remains the same - it is an ArrayList and it will always be an ArrayList. I hope that helps, Corey
|
SCJP Tipline, etc.
|
 |
Anthony Villanueva
Ranch Hand
Joined: Mar 22, 2002
Posts: 1055
|
|
If it helps, you can imagine references as simply different names/labels for the same object, like, "Padme" "Luke Skywalker's Mom" "Natalie Portman's character" but you know a rose by any other name would smell as sweet... [ Jess abusing bartender power to correct Anthony's analogy... she's Luke Skywalker's mom -- not Darth Vader's (that'd be gross) ] [ June 20, 2002: Message edited by: Jessica Sant ]
|
 |
Anthony Villanueva
Ranch Hand
Joined: Mar 22, 2002
Posts: 1055
|
|
Gack! strong is the lure of the Dark Side. My sincerest apologies to all the fans
|
 |
Deepali Pate
Ranch Hand
Joined: Mar 20, 2002
Posts: 114
|
|
Hi, Thanks a lot for your explanations and comments. I must add here that Corey's explantion being simple hepled me most. Thanks guys. Have a nice weekend
|
 |
 |
I agree. Here's the link: jrebel
|
|
subject: Casting a Reference
|
|
|