How does Java Object casting work behind the scene? [duplicate]

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:

Leave a Comment