Please check the below program.
I have doubt when compiler will issue casting exception at compiler level and when it will be at runtime
?
Like in below program, expression
I assumed (Redwood) new Tree()
should have failed at compiler time as Tree is not Redwood. But it is not failing in compile time
, as expected it failed during runtime
!!!
public class Redwood extends Tree {
public static void main(String[] args) {
new Redwood().go();
}
void go() {
go2(new Tree(), new Redwood());
go2((Redwood) new Tree(), new Redwood());
}
void go2(Tree t1, Redwood r1) {
Redwood r2 = (Redwood)t1;
Tree t2 = (Tree)r1;
}
}
class Tree { }
A Tree is not necessarily a Redwood, but it could be, hence the lack of a compile-time error.
In this case it's pretty obvious it isn't, but compilers tend to complain about things that are definitely incorrect, rather than probably or possibly incorrect. In this case the logic is incorrect, not the code itself, and logic is your problem, not the compiler's.
Tree t = new Redwood();
Redwood r = (Redwood) t;
Perfect valid at both compile and run time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With