No. All you are doing is postponing the error to runtime. You should (at great lengths) try to discover all errors at compile time, not try to put them off till runtime. So this is just bad.
Doing B b = (B)new A(); can never succeed because the A is not a B.
In my opinion there isn't any practical purpose to produce code which is guaranteed to crash when you run it.
There could be other purposes, though, for example if you weren't allowed to go home until your code compiled. Then you might want to produce bad code which compiles rather than good code which doesn't compile. However that situation isn't going to apply to made-up code with classes called A and B.
I guess there are two public class in the same package. so it will give a compile time error.
and before casting it is better to check the with "InstanceOf" operator. which will give you a compile time safety.
Ishan Pandya wrote:. . . check the with "InstanceOf" operator. which will give you a compile time safety.
At least two errors there, apart from the spelling error.
1: We are not interested in compile time safety. We want as many errors as possible at compile time. The exception cannot occur at compile time anyway.
2: All you achieve with the instanceof test, which cannot succeed, is obscuring the mistake in code which is never called. It is a version of if(false)... which the compiler cannot detect.
ok Ritchie I understand. So is there any way to get compile time error for "Runtime ClassCastException"? as in can we stop ClassCastException at compile time? as you said that we want as many errors at compile time.
Generics is one method for moving runtime errors to compile time. But that may not be appropriate for this situation.
The correct answer is to design your inheritance hierarchy correctly, so you can use polymorphism and not need those casts in the first place.
Post by:autobot
They worship nothing. They say it's because nothing lasts forever. Like this tiny ad:
a bit of art, as a gift, that will fit in a stocking