十万个为什么?高手解惑,拜托~~~

xiaming 2001-09-24 02:19:58
class Point { int x, y; }
class ColoredPoint extends Point { int color; }
class Test {
public static void main(String[] args) {
ColoredPoint[] cpa = new ColoredPoint[10];
Point[] pa = cpa;
System.out.println(pa[1] == null);
try {
pa[0] = new Point();
} catch (ArrayStoreException e) {
System.out.println(e);
}
}
}



produces the output:
true
java.lang.ArrayStoreException

能给小第一个答案吗?
...全文
82 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
jt80 2001-09-24
  • 打赏
  • 举报
回复
: Norwaywoods(挪威的森林) 的对!
xiaming 2001-09-24
  • 打赏
  • 举报
回复
Testing whether pa[1] is null, will not result in a run-time type error. This is because the element of the array of type ColoredPoint[] is a ColoredPoint, and every ColoredPoint can stand in for a Point, since Point is the superclass of ColoredPoint.
On the other hand, an assignment to the array pa can result in a run-time error. At compile time, an assignment to an element of pa is checked to make sure that the value assigned is a Point. But since pa holds a reference to an array of ColoredPoint, the assignment is valid only if the type of the value assigned at run-time is, more specifically, a ColoredPoint. if not, an ArrayStoreException is thrown.


以上是一位大侠的解释~~~我e文不好,哪位翻译一下~~~大家学习,大家进步!
Yezq_ln 2001-09-24
  • 打赏
  • 举报
回复
补充:

主要看------------------下面的东西
那才是答案。
Yezq_ln 2001-09-24
  • 打赏
  • 举报
回复
如果你有这句:
cpa[0]=new ColoredPoint();

System.out.println(pa[1] == null);

那么你就对了!
----------------------------
ColoredPoint[] cpa = new ColoredPoint[10];
只是定义了一个10个元素的数组,里面的元素没有初始化

for(int i=0;i<10;i++)
cpa[i]=new ColoredPoint();
后才能用数组里的元素。
wilddragon 2001-09-24
  • 打赏
  • 举报
回复
期待答案
Norwaywoods 2001-09-24
  • 打赏
  • 举报
回复
补充:
改为下面的就对了:
class Point { int x, y; }
class ColoredPoint extends Point { int color; }
class Test {

public static void main(String[] args) {
ColoredPoint[] cpa = new ColoredPoint[10];
/*for(int i = 0;i<cpa.length;i++)
{
*/
Point[] pa = cpa;
System.out.println(pa[1] == null);
try {
pa[0] = new ColoredPoint();
} catch (ArrayStoreException e) {
System.out.println(e);
}
}
}
Norwaywoods 2001-09-24
  • 打赏
  • 举报
回复
不对,上面的说法不对,数组在任何位置都会被自动初始化(不管是类成员,还是在方法内声明)错误应该是“pa[0] = new Point();“ 因为pa其实是指向一个ColoredPoint数组,而这里实际上是把用一个派生类指向基类,当然是错的!
hexiaofeng 2001-09-24
  • 打赏
  • 举报
回复
数组没初始化,付值给ColoredPoint[] cpa 就好了

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧