| Author |
How the casting works for classes.
|
Narasimha Rao B.
Ranch Hand
Joined: Aug 26, 2002
Posts: 205
|
|
How the casting works for classes. In the cases of primitves, i excepects it will as follows, float f = 444.444 int i; When assigning f to i by explicit casting i.e., i = (int) f, the most 32 insignificant bits will be assigned to i, bec i can hold at max 32 bits. Is something similar to above will happen when casting for classes.
|
Narasimha
|
 |
Steve Luke
Bartender
Joined: Jan 28, 2003
Posts: 1900
|
|
Casting Classes is different. I can only cast an object to a class type if the object follows the same template as the new class type. For instance: MyClass extends Frame Frame extends Container Container extends Component Component extends Object NewClass extends Frame ... I can cast MyClass to Frame, because MyClass necessarily follows the Frame template, and so on up to Object. Similarly I can cast NewClass the same way up through Object, but can not cast to MyClass since they are not directly related (do not pocess the same template defined in the Class file). I can cast down from Object to classes lower in the class heirarchy only if they match the same template for the lower class. This should always be tested before by doing: Object o = getMyObject(); MyClass mc; if (o instanceof MyClass) mc = (MyClass) o; Casting doesn't reasign any values, it simply tells the JVM to look at a different template when accessing the data stored in the variable. So you can only cast to data types that the stored data can fit... Hope that wasn't too long winded, and helped. Steve
|
Steve
|
 |
Sudharsan Govindarajan
Ranch Hand
Joined: Jul 03, 2002
Posts: 319
|
|
That was a neat explanation Steve! Thanks. sudharsan
|
 |
Dirk Schreckmann
Sheriff
Joined: Dec 10, 2001
Posts: 7023
|
|
When assigning f to i by explicit casting i.e., i = (int) f, the most 32 insignificant bits will be assigned to i, bec i can hold at max 32 bits. This is not a correct understanding of what occurs when casting a float value to an int. The data type float is 32 bits, as is the data type int. A different style of bit pattern is used for floating point data types than is used for integral data types. When casting from float to int, the integer part of the float value is simply used to create the int value. Also note that the floating point literal 444.444 would be considered to be of type double in Java.
|
[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
|
 |
 |
|
|
subject: How the casting works for classes.
|
|
|