Skip to content

Can I cast a superclass into a subclass?

Keiron

Asked Aug 8, 2007, 3:09 AM EDT2 answers
Share
LinkedInX
I thought this would be possible but I get told "Unable to cast object of type Base into type Derived." The Base class is defined in another assembly (not my own), while the Derived class is my own. Is this as expected, or am I doing something wrong?

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0

    Hi Keiron,

    You can cast a variable of a superclass in to a subclass (down-cast) if the superclass variable actually hold a reference to an instance of a the derived class.

    i.e

    Given the class definitions:

    Java
    public class Base{/*members*/}
    public class Derived: Base {/*members*/}
    The following code snipet is ok:
    Base b = new Derived();
    Derived d = (Derived)b;

    However this snipet will raise an exception:

    Base b = new Base();

    Derived d = (Derived)b;

     Hope this helps,

     Sam

    0
  • 0
    Thanks for your help Sam. My issue then is that the object I'm casting *should* be of class Derived, not sure why it isn't - will investigate further. Thanks!
    0