Arrays and Subtyping – Object-Oriented Programming

5.7 Arrays and Subtyping

Table 5.4 summarizes the types found in Java. Only primitive data and reference values can be stored in variables. Only class and array types can be explicitly instantiated to create objects.

Table 5.4 Types and Values

TypesValues
Primitive data typesPrimitive data values
Class, interface, enum, and array types (reference types)Reference values

Arrays and Subtype Covariance

Arrays are objects in Java. Array types (boolean[], Object[], Stack[]) implicitly augment the inheritance hierarchy. The inheritance hierarchy depicted in Figure 5.4, for example, can be augmented by the corresponding array types to produce the type hierarchy shown in Figure 5.6. An array type is shown as a “class” with the [] notation appended to the name of the element type. The class SafeStack is a subclass of the class Stack. The corresponding array types, SafeStack[] and Stack[], are shown as the subtype and the supertype, respectively, in the type hierarchy. Figure 5.6 also shows array types corresponding to some of the primitive data types.

Figure 5.6 Reference Type Hierarchy: Arrays and Subtype Covariance

From the type hierarchy in Figure 5.6, the following facts are apparent:

  • All reference types are subtypes of the Object type. This applies to classes, interfaces, enums, and array types, as these are all reference types.
  • All arrays of reference types are also subtypes of the array type Object[], but arrays of primitive data types are not. Note that the array type Object[] is also a subtype of the Object type.
  • If a non-generic reference type is a subtype of another non-generic reference type, the corresponding array types also have an analogous subtype–supertype relationship. This is called the subtype covariance relationship.
  • There is no subtype–supertype relationship between a type and its corresponding array type.

We can create an array of an interface type, but we cannot instantiate an interface (as is the case with abstract classes). In the following declaration statement, the reference arrayOfISafeStack has type ISafeStack[] (i.e., an array of the interface type ISafeStack):

Click here to view code image

ISafeStack[] arrayOfISafeStack = new ISafeStack[5];

The array creation expression creates an array whose element type is ISafeStack. The array object can accommodate five references of the type ISafeStack. The declaration statement does not initialize these references to refer to any objects; instead, they are initialized to the default value null.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *