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 but when it comes to casting objects I don't understand how it works.
How can a object with the type Object just suddenly be cast to, let's say, MyType
(just an example) and then get all the methods?
Actually, casting doesn't always work. If the object is not an instanceof
the class you're casting it to you will get a ClassCastException
at runtime.
Casting a reference will only work if it's an instanceof
that type. You can't cast random references. Also, you need to read more on Casting Objects
.
e.g.
String string = "String";
Object object = string; // Perfectly fine since String is an Object
String newString = (String)object; // This only works because the `reference` object is pointing to a valid String object.
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
The right way is this:
Integer i = Integer.class.cast(obj);
The method cast()
is a much safer alternative to compile-time casting.
Source: Stackoverflow.com