But why trying to down cast a null object, it doesn't throw NullPointException in Runtime.
eg.
Object o = null;
Integer i = (Integer)o;
Could you please explain it?
Thanks,
Yuan
Ruben Soto
Ranch Hand
Joined: Dec 16, 2008
Posts: 1032
posted
0
Hi Yuan,
The null literal is a special literal of the null type, which denotes that the reference it is assigned to doesn't point to any object.
A reference of any type can be assigned null, and that is why downcasting is working in that sense. Normally, for downcasting you need to consider the actual type of the object involved. But for a null reference there is no object pointed to, so you can cast a null reference to any type.
Yuan Du
Ranch Hand
Joined: Nov 20, 2008
Posts: 34
posted
0
Thank you Ruben!
Yuan
Ruben Soto
Ranch Hand
Joined: Dec 16, 2008
Posts: 1032
posted
0
No problemo! Just remember that you don't cast objects, but references. Upcasting always works, but for downcasting you have to make sure that the actual object's type satisfies the Is-A relationship for the type you are attempting to downcast the reference pointing to that object to.