i am pretty uncomfortable when it comes to downcasting a variable or a object.........
i am trying a lot to grasp the concept of downcasting....by exploring different sites.......but not able to understand.......
please explain methis problem whihc i have written my self......
if i make a object of class B(as it is in middle) like
B b=new B();
then can you explain how many cases will be there for both upcasting and downcasting.........and how they come.......
now the IS-A relationships can be shows as follows
B IS-A A
C IS-A B hence C IS-A A (as B IS-A A)
D IS-A C hence D IS-A B and hence D IS-A A
now the rule is
if the class passes the IS-A test then the up casting is allowed (this is not your question but just giving for people who are a little confused (because I was ))
when it comes do down casting
now suppose we create the object of class B as follows
B b = new B(); // reference is of type B and object is of type B also
and try to downcast it into type C
C c = (C)b; // this will compile fine because type B and C belong to the same inheritance tree but this will result into ClassCastException at runtime because
the object referred by b is of type B and we are referring it by subclass reference variable (this is not possible )
casting any reference variable into any subclass type is OK AT COMPILE TIME but if the object referred by that reference variable is of super class , then referring to it using sub class object results into ClassCastException as said above
look at the following so that you will get clear idea about it
now look at the sample program that will clear all the doubts regarding it
SCJP 6 [86%] June 30th, 2010
OCPWCD [84%] March 26th, 2013
If you find any post useful, click the "plus one" sign on the right
If Foo is the super class of type of b
and D is the sub class of type of b
compiles fine because we can have reference to sub class reference variable or object by super class
but if the object referred by b is of type that is super class of D then it throws the ClassCastException I think you should read my previous post
that will clear most of the doubts
happy to help