Tuesday, June 19, 2012

Reference Variable Casting


This section takes care of Casting(DownCasting and UpperCasting) Downcast: Casting down the inheritance tree to a more specific class The compiler trusts in us even if you're trying to cast object that does not refer a dog. The code above compiles well but you'll get an exception(java.lang.ClassCastException) at runtime, it occurrs because the compiler only verifies an inheritance tree, in this case Dog is a subtype of Animal. !Important Watch out, the code above compiles the exception is throwns at runtime. Upcasting: Unlike downcasting you don't have to type anything like the previous example Dog d = (Dog)a, the upcasting is implicitly, in other words you're restricting the number of methods that you can invoke. Finally the casting can be at one line.

No comments: