package lu.generics;
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();//ArrayStoreException
}catch(Exception e){
print(e);
}
try{
fruit[0]=new Orange();
}catch(Exception e){//ArrayStoreException
print(e);
}
}
import static lu.utils.Print.*;
//创建一个Apple数组,并将其赋值给一个Fruit引用。这是有意义的,因为Apple数组也应该是一个Fruit数组。
//但是如果实际数组类型是Apple[],你因该只能在其中放置Apple或Apple的子类型,这是在编译器和运行时都可以工作。
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();//ArrayStoreException
}catch(Exception e){
print(e);
}
try{
fruit[0]=new Orange();
}catch(Exception e){//ArrayStoreException
print(e);
}
}
}
Output:
java.lang.ArrayStoreException: lu.generics.Fruit
java.lang.ArrayStoreException: lu.generics.Orange