Array Store Check
An array reference exhibits polymorphic behavior like any other reference, subject to its location in the type hierarchy (p. 278). However, a runtime check is necessary when objects are inserted in an array, as illustrated below.
The following assignment is valid, as a supertype reference (Stack[]) can refer to objects of its subtype (SafeStack[]):
Stack[] arrayOfStack = new SafeStack[2]; // (1)
Since Stack is a supertype of SafeStack, the following assignment is also valid:
arrayOfStack[0] = new SafeStack(10); // (2)
The assignment at (2) assigns the reference value of a new SafeStack object to the reference at index 0 in the SafeStack[] object created at (1).
Since the type of arrayOfStack[i], (0 £ i < 2), is Stack, it should be possible to make the following assignment as well:
arrayOfStack[1] = new Stack(20); // (3) ArrayStoreException
At compile time there are no problems, as the compiler cannot deduce that the array variable arrayOfStack will actually denote a SafeStack[] object at runtime. However, the assignment at (3) results in an ArrayStoreException being thrown at runtime because an array of SafeStack objects cannot possibly contain objects of its supertype Stack.
The array store check at runtime ensures that an object being stored in the array is assignment compatible (p. 264) with the element type of the array. To make the array store check feasible at runtime, the array retains information about its declared element type at runtime.
5.8 Reference Values and Conversions
A review of conversions (§2.3, p. 43) is recommended before proceeding with this section.
Reference values, like primitive values, can be assigned, cast, and passed as arguments. Conversions can occur in the following contexts:
- Assignment
- Method invocation
- Casting
The rule of thumb for the primitive data types is that widening conversions are permitted, but narrowing conversions require an explicit cast. The rule of thumb for reference values is that widening conversions up the type hierarchy are permitted, but narrowing conversions down the hierarchy require an explicit cast. In other words, conversions that are from a subtype to its supertypes are allowed, but other conversions require an explicit cast or are otherwise illegal. There is no notion of promotion for reference values.
Leave a Reply