ClassCastException while trying to cast a base class object to..

Discussions

EJB programming & troubleshooting: ClassCastException while trying to cast a base class object to..

  1. Hi All,

    I'm aware that we cannot cast a base class's object to a child class's object. But I have a requirement where in I need to cast a base classes object to child classes object.

    Please help me in doing this. Is there any way we can do this.

    /******************************/
    /* This is quite possible */

    BaseClass baseClass1 = new ChildClass1();
    baseClass1.myBaseClass();
    BaseClass baseClass2 = new ChildClass2();
    baseClass2.myBaseClass();

    /* Throws ClassCastException. */

    ChildClass1 childClass1 = (ChildClass1) new BaseClass();
    childClass1.myBaseClass();
    ChildClass2 childClass2 = (ChildClass2) new BaseClass();
    childClass2.myBaseClass();

    /******************/


    Many thanks in advance,
    Rajesh Artham
  2. ChildClass1 childClass1 = (ChildClass1) new BaseClass()

    Man, this makes no sense. "Fruit a = new Apple()" is valid. "Apple b = new Fruit()" is NOT valid, in ANY language.

    Regards,
    Martin
  3. I agree with you Martin, "Fruit a = new Apple()" is valid. "Apple b = new Fruit()" is NOT valid, in ANY language...

    Rajesh try to relook at the requirements and I am sure somewhere there is a goofup... try to understand the requirements and concepts more clearly.
    Thanks, Anil