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

3 comments:

  1. Their cellular betting app is slick and easy to use, and their buyer ratings are fantastic. Borgata has 카지노 사이트 not been going for too lengthy, and we might anticipate them to enhance over the approaching months and years. Their welcome bonus is simple and easy to clear, with every day bonuses and in-play markets all very attractive.

    ReplyDelete