Forums Register Login

can't understand examlab downcasting question..

+Pie Number of slices to send: Send
source : examlab practice exam 1



this code works fine...but according to me it should give runtime error at commented line but it doesn't. Please clear my doubt
+Pie Number of slices to send: Send
The only reason I can think of is because C is apart of the same inheritance tree as B and B implements m
+Pie Number of slices to send: Send
 

ankur trapasiya wrote:source : examlab practice exam 1this code works fine...but according to me it should give runtime error at commented line but it doesn't. Please clear my doubt

The best guess that I can give is that the value of Null is not type specific. Any type can be "pointed to" Null.
+Pie Number of slices to send: Send
 

The only reason I can think of is because C is apart of the same inheritance tree as B and B implements m


is a reason why the compiler doesn't complain when the downcast is made.

Whereas the reason for not having a run-time error is that the "Run Time Type Identification (RTTI)" or runtime type checking succeeds (It doesn't harm to cast null to C). Even though it looks like you are just performing an ordinary parenthesized cast [b = (C)m], at run time this cast is checked to ensure that it is in fact the type you think it is. If it weren't, you'd have got a ClassCastException. Try using b = (C)a and you will get a runtime error.

So, JVM only checks if the runtime object has the same type or is a subtype of the cast. This act of checking types at runtime is called RTTI.
+Pie Number of slices to send: Send
yes Prashant is correct.

Please note that null in "Min m = null" has nothing to do with no run time error.
+Pie Number of slices to send: Send
still i am not getting this...... It should give me runtime exception because Min is not knowing any of the details about B or C. Please clear this doubt
+Pie Number of slices to send: Send
1) You can cast a reference variable of type Interface to any non-final class even if they are not related. Read this tutorial for more information.
2) You can cast a null value to any type, there is never any ClassCastException in that...
crispy bacon. crispy tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1193 times.
Similar Threads
examlab - 1 [reference variable casting]
Casting problem
Downcasting and upcasting Objects
Assigning references problem
casting from examlab
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 10:59:09.