Suppose B class inherits A. Then the following code works.

A ob;
ob=new B();

but the following throws an ArrayStoreException :

A ob[]=new B[2];
ob[0]=new A();

Is ob[0] a reference of type A or B ? In the first code, ob was a reference of type A and therefore was able to hold a reference of a subtype. In the second code also, ob should be able to hold a reference to both A and B

6 Years
Discussion Span
Last Post by daudiam

Interesting question! My take is:
new B[]; populates the array with two <references to type B>, so the second statement fails because a new A is not a B.
ie: A is a reference to an array that can hold references to type A, but a[0] and A[1] (perfectly validly) hold references to type B.
But I'm not certain.

A ob[]=new B[2];

Thanks. It means that before the above line, ob[0], ob[1].. have no reference type. But after the statement they are assigned the reference type of B. That's why they won't accept references of A again.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.