Type casts are usually an indicator that you should think about an alternative solution for your problem. After all, everything which can be checked at compile time will help the programmer.
However, sometimes type casts are unavoidable and in Generic code they happen often without the programmer ever noticing. Therefore, significant effort was made to make type cast quite fast.
In the past, a runtime type cast included the possibility that the super type hierarchy has to be traversed to find a match. Today, a type cast is nothing more than a number comparison plus a simple pointer comparison, if not optimized away when the analyzer could prove that the cast will always succeed.
In order to make type casting fast, every class knows its depth in the class hierarchy and has a table containing all super types. To test a class, its depth is compared and if the depth is lower, it can’t be a compatible class and the type cast fails. Otherwise, the table’s entry at the position equal to the depth of the check class must match exactly, so that’s all to test.
For example:
Object o=new JButton();
Container c=(Container)o;
Class Container
has a depth of 3 and a the following table of superclasses:
Object
Component
Container
Class JButton
has a depth of 5 and a the following table of superclasses:
Object
Component
Container
JComponent
JButton
Now the type cast checks:
So the hierarchy is not traversed anymore and the type cast operation is rather cheap.