Friday, July 1, 2011

Subtyping in Generics

Before starting on subtyping in Generics, let's first understand what is covariance.
See - What is covariance, contravariance and invariance?

In Java, as in other object-oriented typed languages, hierarchies of types can be built:
 
In Java, a subtype of a type T is either a type that extends T or a type that implements T (if T is an interface) directly or indirectly. Since "being subtype of" is a transitive relation, if a type A is a subtype of B and B is a subtype of C, then A will be a subtype of C too. In the figure above:
  • FujiApple is a subtype of Apple.
  • Apple is a subtype of Fruit.
  • FujiApple is a subtype of Fruit.
Every Java type will also be subtype of Object.

Every subtype A of a type B may be assigned to a reference of type B:

Apple a = ...;
Fruit f = a;


No comments:

Post a Comment

Chitika