In below code, at Line 7 when we are downcasting Tree to Redwood there is no error, but why we get a runtime error at line 10 when downcasting Tree to Redwood
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());// no error here
}
void go2(Tree t1, Redwood r1) {
Redwood r2 = (Redwood)t1;// runtime error here
Tree t2 = (Tree)r1;
}
}
class Tree { }
Well, while a Redwood
instance is always a Tree
instance, not all Tree
instances are a Redwood
. When you create a Tree
instance (with new Tree()
) it is certainly not a Redwood
instance, and cannot be cast to Redwood
.
Redwood r2 = (Redwood)t1;
throws a ClassCastException
when t1
is not a Redwood
. In the first call to go2
, the first argument is new Tree()
, which is not a Redwood
.
Oh, and the reason you see an error here - Redwood r2 = (Redwood)t1;
(line 10) and not on line 7 (go2((Redwood) new Tree(), new Redwood());
) is that line 10 is executed first, at the first call to go2()
(line 6). If you comment line 6, you'll get an exception in line 7.