Wednesday, May 9, 2018

Why downcasting in java is dangerous

By casting we don't cast the real object, but just labelled it in different ways. Cat can be upcast to Animal, but the real object always remains cat, however we labelled it as Animal, however if need to get the properties of cat, we have to downcast from Animal to Cat.

But, if we will try to downcast in inappropriate class type which is not actually referred by the reference variable, then it gives an exception.

For example:

If superclass reference holds the object of subclass then it's okay to type cast, but just imagine if it doesn't…

class A{}

class B extends A{}

A a = new B()

B b = (B)a; // no problem

A a1 = new A();

B b1 = (B)a1; // type cast causes error

No comments:

Post a Comment