Java Cast Under The Hood

Nuwan Zen
2 min readMar 13, 2024

We understand the concept of Java casting and its purpose: facilitating the conversion of data from one type to another. Have you ever think of the internal mechanisms behind this process?

Consider a scenario where Class A inherits from Class B and adds a new method called methodB. When upcasting occurs,

B b = new B();
b.methodB();//does something

A a = (A)b;
a.methodB();//this will not work, it's not accessible

Casting results in the removal of methodB! But how is this achieved? Did the compiler generate a new object for the casting?

Here’s the explanation:

When an object is instantiated, a reference variable is created to hold all the methods associated with that object. Upon casting the object to another type, the compiler adjusts the reference variable to conform to the specifications of Class A. As a result, Class B now has a reference variable that aligns with the specifications of Class A.

What actually occurs is that methodB of Class B becomes obscured from the compiler’s perspective. If you later downcast back to Class B, the reference variable will be adjusted to conform to Class B’s specifications.

This explanation primarily applicable to objects. However, when considering primitive data types, since they do not utilize reference variables, variables are instantiated directly.

--

--

Nuwan Zen

Sometimes A software Engineer, sometimes a support engineer, sometimes a devops engineer, sometimes a cloud engineer :D That’s how the this life goes!