You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: polymorphism.md
+21Lines changed: 21 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -266,3 +266,24 @@ for (Object value : values)
266
266
```
267
267
Java implicitly calls the appropriate inspector on the wrapper class to retrieve the primitive value. The line `sumOfIntegers += i;` is equivalent to
268
268
`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 =newint[] {10, 20, 30};
276
+
if (o instanceofint[])
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:
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