This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Message:
Runtime reference matters
Posted by Kishori Sharan on January 30, 2001 at 7:47 PM
Hello Singh The main thing you have to remeber is that the object reference you are casting must have a valid reference to an object of class type to which you are casting. Suppose you say Class1 c1 = ( Class1 ) c2 ; If at run time c2 has a valid reference to an object of class Class1 then only the above casting is valid. In your case, a a1=new a(); b b1=new b(); b1=(b)a1; in line b1 = ( b) a1 ; a1 must have a valid reference to an object of class b, because b1 is of class b. If you change your line as a a1=new b(); b b1=new b(); b1=(b)a1; then now a1 has a reference to an object of class b and so at run time you won't get any error. When you do casting then at compile time it only checks the correct types. That's all. At run time it will check the type of object reference you are assigning it. In case of the Object class suppose you write Object o = new a (); a aa = ( a) o ; then it will work because o has refernce to an object of type a. But if you do like Object o = new a ( ) ; b bb = (b) o ; then it won't work. Thanx Kishori
Replies:
|