Hi,
There is an example given in the JLS(Page 72 of PDF version) stating that it would compile but would throw ClassCastException
at runtime.Heres the code:
public class Point { int x, y; }
public interface Colorable { void setColor(int color); }
public class ColoredPoint extends Point implements Colorable
{
int color;
public void setColor(int color) { this.color = color; }
}
class
Test {
public static void main(
String[] args)
{
Point[] pa = new Point[100];
// The following line will throw a ClassCastException:
ColoredPoint[] cpa = (ColoredPoint[])pa;
System.out.println(cpa[0]);
int[] shortvec = new int[2];
Object o = shortvec;
// The following line will throw a ClassCastException:
Colorable c = (Colorable)o;
c.setColor(0);
}
}
This class would not compile saying that
Test.java:8: Incompatible type for declaration. Can't convert int[] to Object.Object o=shortvec;
pointing the mistakes to the lines
int[] shortvec = new int[2];
Object o = shortvec;
Going by the JLS rule
If S is an array type SC[], that is, an array of components of type SC :
If T is a class type, then if T is not Object, then a compile-time error occurs(because Object is the only class type to which arrays can be assigned).
Since here the array is being assigned to object it should work fine,then why is it giving compile time error and why does JLS says that it will give runtime errors but not compile time.
Am i missing something here?.Please take time to answer this question.
