Posts Tagged typecasting

Narrowing: Typecasting to Subclass

    Case 1: (ALLOWED):

Super super = new Sub();
Sub sub = (Sub) super;

It is called Narrowing.

We have an object of subclass which is referenced by Superclass reference. We don’t have any other reference to that object. Now we want to get subclass reference to that object to get access to subclass methods. Then we can perform narrowing. Here object remains the same(of subclass), what narrowing does is gives a reference of subclass to that object.

Case 2: (Gives ClassCastException at run time):

Super super = new Super();
Sub sub = (Sub) super;

If object itself is of superclass, we can not have a reference of subclass to it. The superclass object does not have subclass specific members in its scope. So if it is typecasted to subclass, it will still have the superclass members in its scope, so there is no use of narrowing it to subclass. So it is not allowed.
Why the error is at run time, not compile time: At compile time, the compiler does not know what object the super class reference is pointing to. Compiler knows about the reference variable only.
If it points to subclass,

Super super = new Sub();

Narrowing is allowed as in case 1 above.
But if it points to same(super) class, narrowing is not allowed.

Super super = new Super();

So not knowing what the actual case is,compiler does not take any action and leaves it to run time to handle it.


Leave a comment