Skip to content

Commit 34586aa

Browse files
authored
Polymorphism and arrays
1 parent 4151481 commit 34586aa

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

polymorphism.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,3 +266,24 @@ for (Object value : values)
266266
```
267267
Java implicitly calls the appropriate inspector on the wrapper class to retrieve the primitive value. The line `sumOfIntegers += i;` is equivalent to
268268
`sumOfIntegers += i.intValue();`. Similarly, `sumOfIntegers += (int)values[1];` is equivalent to `sumOfIntegers += ((Integer)values[1]).intValue();`.
269+
270+
## Polymorphism and arrays
271+
272+
Arrays are involved in polymorphism in two ways:
273+
- Arrays are objects, so array references can be assigned to variables of type `Object`:
274+
```java
275+
Object o = new int[] {10, 20, 30};
276+
if (o instanceof int[])
277+
assert ((int[])o)[2] == 30;
278+
```
279+
- Arrays are *covariant*. That means that if T is a class, a variable of type `T[]` can refer to an array whose element type is T or a subclass of T. For example:
280+
```java
281+
Circle[] myCircles = {new Circle(5, 10, 5), new Circle(10, 20, 10)};
282+
Shape[] myShapes = myCircles; // OK, Circle is a subclass of Shape
283+
```
284+
This means, however, that a run-time check is generally necessary to ensure that objects assigned to array components are of the array's element type:
285+
```java
286+
myShapes[0] = new Circle(10, 5, 10); // OK
287+
myShapes[1] = new Polygon(10, 20, 30, 40, 50, 60); // Throws ArrayStoreException
288+
```
289+
Since the static type of `myShapes` is `Shape[]` and `Polygon` is a subclass of `Shape`, Java's static type checker accepts the assignment of a `Polygon` object to a component of the array. However, since `myShapes` refers to an array with element type `Circle` (i.e. its dynamic type is `Circle[]`), execution of the assignment fails with an `ArrayStoreException` at run time.

0 commit comments

Comments
 (0)