Back to series
· 9 min read

Subtyping, Covariance, and Contravariance


I. What Is Subtyping

Subtyping is a relationship in type systems used to describe whether one type can be safely used in a position where another type is required.

If type B is a subtype of type A, it is usually written as:

B <: A

This means that B can be used in scenarios that require A.

The key point here is substitutability, not merely inheritance.

For example:

class Animal {
    void eat() {}
}

class Dog extends Animal {
    void bark() {}
}

class Cat extends Animal {
    void meow() {}
}

In Java:

  • Dog is a subtype of Animal.
  • Cat is a subtype of Animal.
  • Animal is the parent type (supertype) of Dog.

Therefore, a Dog object can be assigned to a variable of type Animal:

Animal animal = new Dog();

But the reverse does not hold:

Dog dog = new Animal(); // compile error

The reason is that an arbitrary Animal does not necessarily have the behavior of a Dog.

1. The Difference Between Subtyping and Inheritance

Inheritance is a mechanism for reusing code and establishing a class hierarchy; subtyping is a compatibility relationship in the type system.

The two are related, but they are not equivalent.

Comparison dimension Inheritance Subtyping
Level Object-oriented implementation mechanism Type system relationship
Core purpose Reuse implementation, extend behavior Guarantee type substitutability
Requires an inheritance relationship Yes, for class inheritance Not necessarily
Involves type compatibility Usually yes Type compatibility is the core
Typical example Java extends Go interfaces, TypeScript structural types

For example, in Go:

type Animal interface {
    Eat()
}

type Dog struct{}

func (Dog) Eat() {}

Dog does not explicitly inherit from Animal, but because it implements the methods required by the interface, it can satisfy the Animal type constraint.

TypeScript also adopts structural type compatibility rules:

type Animal = {
    eat(): void;
};

type Dog = {
    eat(): void;
    bark(): void;
};

const dog: Dog = {
    eat() {},
    bark() {}
};

const animal: Animal = dog;

Dog has the structure required by Animal, so it can be assigned to Animal.

2. Subtyping and the Liskov Substitution Principle

Subtyping is closely related to the Liskov Substitution Principle (LSP).

The Liskov Substitution Principle emphasizes:

If B is a subtype of A, then wherever A is used, it should be possible to safely use B without breaking the original correctness of the program.

This requires not only that method names match, but also that behavioral contracts are compatible.

For example:

class Bird {
    void eat() {}
}

class Sparrow extends Bird {
    void fly() {}
}

Sparrow can be used as a Bird because it preserves the basic behavior of Bird.

But if it is designed like this:

class Bird {
    void fly() {}
}

class Penguin extends Bird {
    @Override
    void fly() {
        throw new UnsupportedOperationException();
    }
}

Although the penguin inherits from Bird, it cannot properly fulfill the behavioral contract of fly().

This shows that an inheritance relationship does not necessarily imply a sound subtyping relationship.

Subtyping requires behavioral substitutability, not just a syntactic inheritance relationship.

II. What Is Variance

Variance describes whether, when there is a subtyping relationship between type parameters, a corresponding subtyping relationship also exists between the generic types, and what the direction of that relationship is.

Suppose:

Dog <: Animal

For a generic type Container<T>, we need to answer:

  • Is Container<Dog> a subtype of Container<Animal>?
  • If so, is the direction of the relationship the same as that of the type parameters?
  • Should it be the reverse?
  • Are the two incompatible?

Based on the answer, variance falls into three categories:

Type English Type Parameter Relationship Generic Relationship
Covariance Covariance Same direction Same direction
Contravariance Contravariance Opposite direction Opposite direction
Invariance Invariance Does not establish a subtype relationship Does not establish a subtype relationship

Assume:

Dog <: Animal

Then:

Covariance:

Dog <: Animal
Container<Dog> <: Container<Animal>

Contravariance:

Dog <: Animal
Consumer<Animal> <: Consumer<Dog>

Invariance:

Container<Dog> \not<: Container<Animal>

At the same time:

Container<Animal> \not<: Container<Dog>

The key here is not the name of the generic type, but how the generic type parameters are used in the type definition.

3. Covariance

Covariance means that when the type parameter changes from a supertype to a subtype, the generic type as a whole also maintains a subtype relationship in the same direction.

If:

Dog <: Animal

then a covariant container satisfies:

Container<Dog> <: Container<Animal>

That is, a container holding Dog can be used where a container of Animal is needed.

1. Intuitive understanding of covariance

Suppose there is an interface responsible only for reading animals:

interface Producer<T> {
    T get();
}

Producer<Dog> only produces Dog, and Dog itself is Animal.

Therefore, the caller can use it entirely as Producer<Animal>.

For example:

Producer<Dog> dogProducer = ...;
Producer<? extends Animal> animalProducer = dogProducer;

Animal animal = animalProducer.get();

Here ? extends Animal means the type parameter is Animal or one of its subtypes.

The caller can safely read an Animal, because the object actually returned is guaranteed to be a subtype of Animal.

2. Why covariance is suitable for producers

A producer only supplies data outward.

Suppose:

interface Producer<T> {
    T get();
}

When T is Dog:

  • get() returns Dog.
  • Dog can always be assigned to Animal.
  • The caller only requires an Animal and does not care whether it is a more specific Dog.

Therefore, covariance is suitable for scenarios that only output the type parameter.

3. Covariance in Java

Java generics are invariant by default, but use-site covariance can be achieved through the wildcard ? extends.

class Animal {}

class Dog extends Animal {}

class Cat extends Animal {}

static void printAnimals(List<? extends Animal> animals) {
    for (Animal animal : animals) {
        System.out.println(animal);
    }
}

All of the following calls compile:

List<Dog> dogs = new ArrayList<>();
List<Cat> cats = new ArrayList<>();

printAnimals(dogs);
printAnimals(cats);

Because List<? extends Animal> can accept a list whose type parameter is Animal or any of its subtypes.

4. Write Restrictions of Covariance

A covariant container has an important limitation: you cannot safely write concrete subtype objects into it.

List<? extends Animal> animals = new ArrayList<Dog>();

animals.add(new Dog()); // compile error
animals.add(new Cat()); // compile error

Why?

Because the compiler cannot determine what the actual element type of animals really is:

  • List<Dog>
  • List<Cat>
  • List<Animal>

If writing a Cat were allowed while the actual object is a List<Dog>, type safety would be broken.

However, you can write null, because null can be assigned to any reference type.

The core rules of covariant containers:

  • You can read elements as the supertype.
  • You cannot write concrete non-null elements.
  • Suitable for data production and read-only access.

Note that Java's List<? extends Animal> does not mean the underlying list is truly unmodifiable. What it restricts is type-safe writes through the current reference, not turning the object itself into an immutable collection.

IV. Contravariance

Contravariance means: as the type parameter goes from a supertype to a subtype, the subtype relationship of the generic type as a whole reverses.

If:

Dog <: Animal

then the contravariant relationship satisfies:

Consumer<Animal> <: Consumer<Dog>

In other words, a consumer that can handle any Animal can certainly handle a Dog as well.

1. An Intuitive Understanding of Contravariance

Suppose there is an interface whose only job is to consume animals:

interface Consumer<T> {
    void accept(T value);
}

Now consider two consumers:

  • Consumer<Animal>: can accept any animal.
  • Consumer<Dog>: can only accept dogs.

If the caller only ever passes in Dog, then a consumer that can accept any Animal can obviously handle Dog too.

Therefore:

Consumer<Animal> <: Consumer<Dog>

The direction is opposite to the subtype relationship of the original types.

2. Why Contravariance Suits Consumers

A consumer only receives data and does not return the type parameter outward.

interface Consumer<T> {
    void accept(T value);
}

If T is Animal, then it can accept:

  • Dog
  • Cat
  • Other subtypes of Animal

So as long as the caller provides a Dog, a consumer that accepts Animal is sufficient.

Contravariance suits scenarios such as parameter input, event handling, callback functions, and comparators.

3. Contravariance in Java

Java can use ? super to express contravariance at the use site.

class Animal {}

class Dog extends Animal {}

static void addDog(List<? super Dog> animals) {
    animals.add(new Dog());
}

All of the following types can be passed in:

List<Dog> dogs = new ArrayList<>();
List<Animal> animals = new ArrayList<>();
List<Object> objects = new ArrayList<>();

addDog(dogs);
addDog(animals);
addDog(objects);

Because the element type of all these lists is Dog or a supertype of Dog.

4. Read Restrictions of Contravariance

List<? super Dog> animals = new ArrayList<Animal>();

animals.add(new Dog()); // valid

Dog dog = animals.get(0); // compile error
Object value = animals.get(0); // valid

Why can a read safely yield only Object?

Because animals may actually be:

  • List<Dog>
  • List<Animal>
  • List<Object>

An element retrieved from it may be a Dog, another Animal, or even some other object.

Therefore, the compiler can only guarantee that the result of a read is at least Object.

The core rules of a contravariant container:

  • You can write values of the specified subtype.
  • When reading, you can usually only safely obtain Object.
  • It is suitable for consuming data and for parameter input.

V. Invariance

Invariance means: even if the type arguments have a subtype relationship, the generic type as a whole does not establish a corresponding subtype relationship.

If:

Dog <: Animal

then:

Container<Dog> \not<: Container<Animal>

and:

Container<Animal> \not<: Container<Dog>

1. Why Invariance Is Needed

Suppose the following were allowed:

List<Dog> dogs = new ArrayList<>();
List<Animal> animals = dogs;

Then a Cat could be added to the list through animals:

animals.add(new Cat());

At this point, a Cat has appeared in the collection originally declared as List<Dog>.

Subsequent code:

Dog dog = dogs.get(0);

could then cause a type error at runtime.

Therefore, if a generic container allows both reading and writing of its type parameter, then without additional constraints it generally needs to be invariant.

2. Java Generics Are Invariant by Default

Java generics are invariant by default.

List<Dog> dogs = new ArrayList<>();

List<Animal> animals = dogs; // compile error

Although Dog is a subtype of Animal, List<Dog> is not a subtype of List<Animal>.

This is an important part of the type-safety design of Java generics.

3. Invariance Does Not Mean You Cannot Read and Write

Invariance only means that there is no subtype-compatibility relationship between generic instances with two different type arguments.

For an explicit List<Dog>, you can still read and write Dog normally:

List<Dog> dogs = new ArrayList<>();

dogs.add(new Dog());

Dog dog = dogs.get(0);

Invariance restricts the type-substitution relationship between different generic instances, not the container's own ability to operate.

VI. Comparison of Covariance, Contravariance, and Invariance

Suppose:

Dog <: Animal

The differences between the three kinds of variance are as follows:

Variance Type Generic Relationship Main Use Typical Direction
Covariance Producer<Dog> can be used in place of Producer<Animal> Produces data Output
Contravariance Consumer<Animal> can be used in place of Consumer<Dog> Consumes data Input
Invariance Neither can be used in place of the other Reads and writes simultaneously Input and output

A simple principle can help you understand them:

  • Covariance: outputs a more specific type, satisfying callers that need a more general type.
  • Contravariance: accepts a more general type as input and can handle the more specific types provided by callers.
  • Invariance: input and output affect each other, so the compatibility direction of the type parameter cannot be changed arbitrarily.

VII. Covariance and Contravariance in Function Types

Covariance and contravariance exist not only in generic containers but also in function types.

A function type can be represented as:

A \rightarrow B

where:

  • A is the parameter type.
  • B is the return type.

For function types, the usual rules are:

  • Return types are covariant.
  • Parameter types are contravariant.

This is a very important — and easily confused — part of variance.

1. Covariant return types

Suppose:

Dog <: Animal

Now consider two functions:

f1: () -> Dog
f2: () -> Animal

f1 returns Dog, and a Dog can be used as an Animal.

Therefore, any caller that needs an Animal returned can use a function that returns Dog.

So:

() \rightarrow Dog <: () \rightarrow Animal

The return type may narrow from a supertype to a subtype; this is return type covariance.

2. Contravariant parameter types

Suppose:

Dog <: Animal

There are two functions:

f1: Animal -> void
f2: Dog -> void

f1 can accept any Animal, and of course it can also accept a Dog.

But f2 can only accept a Dog.

If a caller needs a function that can handle any Animal, it cannot simply be passed a function that can only handle Dog.

But if the caller only ever passes in Dog, then f1 is entirely adequate.

Therefore:

(Animal \rightarrow void) <: (Dog \rightarrow void)

The direction in which parameter types are compatible is the reverse of the subtype relation; this is parameter contravariance.

3. The complete relationship of function variance

Suppose:

Dog <: Animal

Then:

Dog \rightarrow Dog <: Animal \rightarrow Animal

Here:

  • The input parameter goes from Animal to Dog, which is the contravariant direction.
  • The return value goes from Dog to Animal, which is the covariant direction.

The complete rule for function types can be written as:

(S_1 \rightarrow T_1) <: (S_2 \rightarrow T_2)

When:

S_2 <: S_1

and:

T_1 <: T_2

then, and only then, does the function type have the corresponding subtype relation.

That is:

  • Parameter types are compatible in the opposite direction.
  • Return types are compatible in the same direction.

4. Examples of function variance

TypeScript:

class Animal {}

class Dog extends Animal {}

type AnimalHandler = (value: Animal) => void;
type DogHandler = (value: Dog) => void;

const handleAnimal: AnimalHandler = (value) => {
    console.log(value);
};

const handleDog: DogHandler = handleAnimal;

handleAnimal can handle all animals, so it can also handle a Dog.

But the reverse:

const handleAnimal2: AnimalHandler = handleDog;

Under strict function type checking, this assignment is usually not valid, because handleDog cannot guarantee that it handles any Animal.

Note: TypeScript has a historical design difference between method parameters and function-valued property parameters in compatibility checking, and method declarations may use a looser bivariant rule. When analyzing code, judge based on strictFunctionTypes and the specific declaration form.

8. Why inputs are contravariant and outputs covariant

This can be derived from the perspective of type safety.

Suppose a function must satisfy the following contract:

Input: Animal
Output: Animal

The caller may pass in any Animal and expects to get back an Animal.

Now consider replacing it with another function:

Input: Dog
Output: Dog

It has two problems:

  1. It can only accept Dog and cannot handle Cat.
  2. Although it returns Dog, that part is fine, because a Dog can be used as an Animal.