数组没初始化,付值给ColoredPoint[] cpa 就好了

解决方案 »

  1.   

    不对,上面的说法不对,数组在任何位置都会被自动初始化(不管是类成员,还是在方法内声明)错误应该是“pa[0] = new Point();“ 因为pa其实是指向一个ColoredPoint数组,而这里实际上是把用一个派生类指向基类,当然是错的!
      

  2.   

    补充:
         改为下面的就对了:
                          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);
    }
    }
    }
      

  3.   

    如果你有这句:
    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();
    后才能用数组里的元素。
      

  4.   

    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文不好,哪位翻译一下~~~大家学习,大家进步!
      

  5.   

    : Norwaywoods(挪威的森林) 的对!