GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting issues Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting issues" Watch "Casting issues" New topic
Author

Casting issues

Wilson Mui
Ranch Hand

Joined: Apr 09, 2003
Posts: 140
Ok, I'm on a posting binge.
I just wanted to get this clear, because after missing this one question on the John Hunt exam, it is turning my world upside down.
Ok implicit casting. If I want to do an implicit casting, the object that I am trying to implicitly cast, must be of the same or smaller type than the object that is to contain it. Meaning
int i = s // a short
int i = c // a char, not even sure if that is possible
short s = b // a byte
but I can use explicit casting to do almost anything I please...meaning the explicit cast will be chopping off information just to make it fit. Like if I tried to do
byte b = (byte)s // as short
the (byte) casting will just chop all the information off the s.
If that is the case, does the explict casting do the same type of "chopping" to objects? Like if I did a Car myCar = (Car)H*nda explicit casting, will myCar just be a Car again, or will "H*nda Information" still linger somewhere, so that if I did a (H*nda)myCar, all the "Honda Information" will come back
Bryan Helm
Greenhorn

Joined: Apr 07, 2003
Posts: 20
Casting of references does not effect the object pointed to by the reference but it can certainly effect the behavior of the code. The reference type is used to determine what member variables amd static methods to access, and will also determine where the search for an overridden method starts - if the class of the reference does not declare a method of the actual class of the object, then you cannot call that method with that reference without explicitly casting to the subclass (downcasting). Note that no cast is necessary to cast to a superclass - implicit upcasting is allowed. Another difference between explicit casting of primitives to smaller types and reference casting is that primitive casting will not result in an exception, just possible loss of information, but reference casting will give you a ClassCastException if the actual type of the object is not compatible with the reference being cast to.
 
GeeCON Prague 2014
 
subject: Casting issues