I wonder if anyone could tell me how casting works? I understand when I should do it, but not really how it works. On primitive data types I understand partially bu
Suppose you wanted to cast a String
to a File
(yes it does not make any sense), you cannot cast it directly because the File
class is not a child and not a parent of the String
class (and the compiler complains).
But you could cast your String
to Object
, because a String
is an Object
(Object
is parent). Then you could cast this object to a File
, because a File is an Object
.
So all you operations are 'legal' from a typing point of view at compile time, but it does not mean that it will work at runtime !
File f = (File)(Object) "Stupid cast";
The compiler will allow this even if it does not make sense, but it will crash at runtime with this exception:
Exception in thread "main" java.lang.ClassCastException:
java.lang.String cannot be cast to java.io.File