for each循环的一个奇怪现象!

ankyhe ankyhe 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
看下面这段代码:
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();

}
}
可以顺利通过编译运行,一点异常都没有。
请问这两种写法有什么不同吗,为什么结论不一样?
...全文
评论 4
收藏 已收藏
分享
返回顶部
ankyhe
Java SE 62,621 成员 307,251 内容