• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt about ArrayStoreException

 
Vishal Malu
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I came across this example in JLS 3.0 page 328

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

I didn't understand why pa[0] = new Point(); gives the ArrayStoreException.
Can nebody explain it??
 
amit taneja
Ranch Hand
Posts: 813
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is because the array is actually of type ColoredPoint which is now reference by superclass array type...but note that ..only refence is changed

inside the array all the reference index element are of point type and can only refer to opjects of ColoredPoint or any Subclass of Colored point..

if you get the point of last line... then fine...
else pls read inheritence....

as reference variable can refer to the object of type its declared or its subclass type...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic