Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting a Reference

 
Deepali Pate
Ranch Hand
Posts: 114
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gack! strong is the lure of the Dark Side. My sincerest apologies to all the fans
 
Deepali Pate
Ranch Hand
Posts: 114
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic