Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting Object References

 
Shiaber Shaam
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When we type cast object references..... we are casting the references or objects.... Plz clarify......
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are casting the reference type. You can't cast an object.
 
Shiaber Shaam
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok.. then when do we need to cast references... can u explain some scenarios.... or rules.....
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One situation where you need to cast references is if a method has a formal parameter which is a supertype of the actual parameter, then when the method is called, that reference will be widened. You have to cast the reference back to the type it was before if you want to call methods on the reference that are defined in the subclass.

Consider this example.



This will produce a compile-time error because no matter what reference type you send to equals, it will be widened to an Object reference.

The class Object does not define the method num().

So you can only call methods on o that are defined in Object.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic