【发布时间】: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