down casting

Discussions

EJB design: down casting

  1. down casting (6 messages)

    what is called down casting. what will happend when down casting is used.

    Threaded Messages (6)

  2. down casting[ Go to top ]

    This isn't an EJB question but sine it is x-mas... :-)

    If you have a class hierarchy where class B extends class A (B is a specialization of A) you can use B in the place of A since B supports all the operations that B does. This is called polymorphism.

    When you use an object of type B in place of A you actually do a up-cast, meaning you make the object of type B look like an object of type A (a less specific class type).

    What you are asking about is down-casting which is making an object be of a more specific type, i.e. transforming an object of type A to type B. Is is only allowed if the object was actually created as a type B.

    This is allowed (line 2 is a down-cast):
    A a = new B();
    B b = (B)a;

    This will throw a ClassCastException (line 2 is an invalid down-cast):
    A a = new A();
    B b = (B)a;

    The down-cast in example 2 is invalid since an object created as type A doesn't necessarily support all the operations type B does.

    Hopes this answers your question...
  3. DownCasting[ Go to top ]

    class A
    {
    }
    class B extends A
    {
    }

    A a = new A();
    B b = new B();

    //Downcasting
    b= (B)a;

    //UpCasting
    A= (A)b;

    When you go up in hirarchy it is upcasting
    When you go down in hirarchy it is downcasting
  4. Oh your answer[ Go to top ]

    Downcasting gives run time error
  5. Downcasting is just to amuze the compiler. At the runtime, VM will approve or reject it if the object is not of the correct type.
  6. down casting[ Go to top ]

    It is a dangerous option in Object Oriented paradigm but
    it is used extensively in J2EE.

    Thanks,
    Badrish
  7. check[ Go to top ]

    Thats why if possible you should check by using
    if(a instance of B)
    a= (B)b