看下面这段代码:
class Employee{
}
class Manager extends Employee{
}
public class InheritanceTest {
    public static void main(String[] args) {
        Manager[] ms = new Manager[10];
        Employee[] es = ms;
        for(int i = 0 ; i < es.length; ++i)
            es[i] = new Employee();
           
    }
}
这样可以编译,但是在运行时会有一个ArrayStoreException异常。
但是如果将代码改为
class Employee{
}
class Manager extends Employee{
}
public class InheritanceTest {
    public static void main(String[] args) {
        Manager[] ms = new Manager[10];
        Employee[] es = ms;
        for(Employee elem:ms)
             elem = new Employee();
           
    }
}
可以顺利通过编译运行,一点异常都没有。
请问这两种写法有什么不同吗,为什么结论不一样?

解决方案 »

  1.   

    第一种由于向Manager数组中写入Employee,所以报错
    第二种根本就不会存入到数组,所以没报错
      

  2.   

    这两种写法不是一样的意思嘛,kingfish能不能解释的清楚些?
      

  3.   

    你可以把for each后数组内容打出来看看,应该都是null第二种大致相当与:
        Employee elem = null;
        for (int i = 0; i < ms.length; ++i) {
          elem = ms[i];
          elem = new Employee();
        }