I'm studying for the SCJP exam, and I'm writing some sample code to further examine the self-test questions from the SCJP 6 Study Guide. I am confused as to why there is no ClassCastException when we say:
Why am I allowed to downcast a Tree to a Redwood? I'm guessing it has something to do with the fact that the object is not referenced by a reference variable, but that's a shot in the dark. I am satisfied with the reason it happens when we say:
It's because the compiler remove any unnecessary casting. Since go2() takes Tree as first argument, and your object is already a Tree object..it just removed the casting.
If you have another overloaded method called go2(Rainwood, Rainwood), then the compiler will keep your casting because it figures you are trying to select which specific method to call and you will get the exception during runtime.
Play around will javap and you'll see what the compiler does with the casting in the bytecode.
Originally posted by Wirianto Djunaidi: It's because the compiler remove any unnecessary casting. Since go2() takes Tree as first argument, and your object is already a Tree object..it just removed the casting.
I modified the code and tried it. I commented the first call to go2 and displayed a message before the cast in go2. Now according to you the cast in the call to go2 will be removed. Then the message "No Exception" must be displayed and then a ClassCastException must be thrown at (1). But its not that case. The ClassCastException comes before the message is displayed. This means that the compiler didn't remove the cast...