The Java Program: Sub.java
1 // Sub.java -- subtyping and array assignment
2
3 public class Sub {
4
5 static class Base { int x = 1; }
6 static class Derived extends Base { int y = 11; }
7
8 static void g (Base s, Base e) { s = e; }
9
10 static void h (Base[] array, Base e) {
11 array[0]=e; // java.lang.ArrayStoreException possible
12 }
13
14 public static void main (String args[]) {
15 final Derived [] da = new Derived [10];
16 final Base [] ba = new Base [10];
17 final Base a = new Base (); a.x =8;
18
19 // In the next call to "g", the local variable "s" is initialized
20 // to the value of "ba[0]" (null). "a" is assgined to local
21 // variable "b", but because all parameters are passed call-by-
22 // value, no value is assigned to "ba[0]" (it is still null).
23 g (ba[0], a);
24
25 // The array "ba" is updated; no problem
26 h (ba, a);
27 System.out.println (ba[0].x); // Outputs: "8"
28
29 // In the next call to "g", the local variable "s" is initialized
30 // to the value of "da[0]", but that's fine (because it is a
31 // widening). "a" is assigned to local variable "b", but because
32 // all parameters are passed call-by-value, no value is assigned
33 // to "da[0]".
34 g (da[0], a);
35
36 // The array "da" is updated with a "Derived" value.
37 h (da, new Derived());
38 System.out.println (da[0].y); // Outputs: "11"
39
40 // The array "da" of "Derived" values cannot be updated with
41 // a "Base" value; a java.lang.ArrayStoreException is raised.
42 h (da, a);
43 System.out.println (da[0].y); // What would be "y"'s value?!
44 }
45 }