在下面的程序中,我希望没有例外。使用go2
go() 方法中的方法,我收到异常错误“无法将树转换为 Redwood”。
对我来说,这只是沮丧,应该完全没问题。有人可以帮我理解为什么会抛出异常吗?
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();
}
}
}
}