【问题标题】:Runtime upcasting failure from Thinking in Java来自 Thinking in Java 的运行时向上转换失败
【发布时间】:2018-04-04 13:50:13
【问题描述】:

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

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); }
    }
}

【问题讨论】:

  • 数组是Apple[]。你为什么期望它能够容纳不是Apple 的东西?

标签: java runtime-error upcasting


【解决方案1】:

原因是因为您试图将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
    }
}

【讨论】:

    【解决方案2】:

    尝试放入数组类型:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-24
      • 2013-04-11
      • 1970-01-01
      相关资源
      最近更新 更多