In below program I am expecting no exception. With go2 methods in go() method I am getting an exception error " Tree can not be cast to Redwood ".
For me it is just downcasting, it should be perfectly OK. Can someone help me understand why there is exception thrown?
class Tree{ }
class Redwood extends Tree {
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;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Redwood().go();
}
}
>> a similar program and this one works fine .
class Animal2 {
static void doStuff(){
System.out.println("a " );
}
}
class Dog extends Animal2{
static void doStuff(){
System.out.println("b ");
}
void playdead(){ System.out.print(" ccc" + "\n");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Animal2[] a= {new Animal2(), new Dog(), new Animal2()};
for(Animal2 animal : a)
{
animal.doStuff();
if(animal instanceof Dog)
{
((Dog) animal).playdead();
}
}
}
}