-
what is called down casting. what will happend when down casting is used.
-
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...
-
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
-
Downcasting gives run time error
-
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.
-
It is a dangerous option in Object Oriented paradigm but
it is used extensively in J2EE.
Thanks,
Badrish
-
Thats why if possible you should check by using
if(a instance of B)
a= (B)b