Possible Duplicate:
How does the Java cast operator work?
Java casting implementation
I am always wondering how object casting works in Java. I understand for primitive type it will be more like in binary representation level, but what about Object? Is it kind of like Polymorphism
or dynamic binding
in that everything will be determined at runtime? For example:
class Parent{
void A(){}
}
class Child extends Parent{
@Override
void A(){}
}
Parent p = new Parent();
Child c = (Child) p;
How does this work behind the scene? Does it create a new instance of Child
? And also, what happens if you try to cast:
Child b = (Child) new Object();
And last one, when casting a primitive to a wrapper class:
Double d = (Double) 3.3;
I know you don't necessary need to cast it, but what if you do? Is there anything significant that happens on the backend?
No new objects are created in the system when you use explicit casting (except in your last case, where you cast a primitive type to an object wrapper, since double
is not an object like Double
is). Note that this explicit cast isn't necessary due to Java's autoboxing feature.
In your (Child) new Object()
scenario, you will receive a ClassCastException because an Object
is not a Child
(although the opposite is true).
The answer to your first scenario is the most complicated. Essentially the parent class is treated like an interface might be. When you cast the Child
to the Parent
, only the Parent
API is available. However, the overridden method will still be called. So, if you do:
Parent p = (Parent) new Child();
p.a();
... the Child
's public void a()
will be called, even though it is being seen through the lens of the Parent
class. However if you were to have a second method in the Child
that the Parent
does not have (let's say public void b()
for instance), you would not be able to call that without casting the object back to a Child
.
"Behind the scenes", as you say, the only new thing that is created is another object reference which points to the same object. You can have as many references as you like to the same, singular object. Consider this example:
Parent p = new Parent();
Parent p1 = p;
Parent p2 = p;
Parent p3 = p2;
Here, there are four references (p
, p1
, p2
, and p3
) each of which points to the same object you created with the new Parent()
declaration.
I would probably argue on the philosophical point, though, that this creation of new references is actually explicit rather than behind the scenes when you say Parent p = something
.
Links: