在下面的程序中我预计不会有异常(exception)。使用 go() 方法中的 go2
方法,我收到异常错误“Tree can not be Cast to 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();
}
}
}
}
最佳答案
红木是一种树。树不是红杉的一种,就像所有动物都不是猫一样。所以这不起作用:
(Redwood)new Tree()
但这会:
(Tree)new Redwood()
也许你的意思是:
void go() {
go2(new Tree(), new Redwood());
go2(new Redwood(), new Redwood());
}
Java 将在第二次调用中自动使用第二个红木作为 go2
的树。
关于java - 为什么我在简单的 java 程序中遇到 ClassCastException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11434962/