来自 Thinking in Java 的运行时向上转换失败



运行此代码时,为什么会出现运行时错误?数组被定义为保存水果,但是在我用苹果初始化它之后,我怎么能不给它水果呢?

class Fruit{}
class Apple extends Fruit{}
class Jonathan extends Apple{}
class Orange extends Fruit{}
public class CovariantArrays {
    public static void main(String[] args) {
        Fruit[] fruit = new Apple[10];
        fruit[0] = new Apple();
        fruit[1] = new Jonathan();
        try {
            fruit[0] = new Fruit();
        } catch(Exception e) { System.out.println(e); }
        try {
            fruit[0] = new Orange();
        } catch(Exception e) { System.out.println(e); }
    }
}
原因是

因为您正在尝试将FruitOrange放入Apple中。你只能把东西放在里面Apple[]如果它真的是一个苹果,例如

class Fruit{}
class Apple extends Fruit{}
class Jonathan extends Apple{}
class Orange extends Fruit{}
class BigApple extends Apple{}
class BigGreenApple extends BigApple{}
public class CovariantArrays {
    public static void main(String[] args) {
        Fruit[] fruit = new Apple[10];
        fruit[0] = new Apple();
        fruit[1] = new Jonathan(); // no error here since Jonathan is an Apple
        fruit[2] = new BigApple(); // still Apple
        fruit[3] = new BigGreenApple(); // no worries - still Apple
        fruit[4] = new Orange(); // Oops - Orange is a Fruit but its not Apple so error here
    }
}

尝试将其放入数组类型:

fruit[0] = (Fruit) new Apple();

相关内容

  • 没有找到相关文章

最新更新