Behavioral subtyping

In object-oriented programming, behavioral subtyping is the principle that subclasses should satisfy the expectations of clients accessing subclass objects through references of superclass type, not just as regards syntactic safety (such as the absence of "method-not-found" errors) but also as regards behavioral correctness.

Most programming language compilers ignore documentation and perform only the checks that are necessary to preserve type safety.

In contrast, a program where both Stack and Queue are subclasses of a type Bag, whose specification for get is merely that it removes some element, does satisfy behavioral subtyping and allows clients to safely reason about correctness based on the presumed types of the objects they interact with.

A type S is a behavioral subtype of a type T if each behavior allowed by the specification of S is also allowed by the specification of T. This requires, in particular, that for each method M of T, the specification of M in S is stronger than the one in T. A method specification given by a precondition Ps and a postcondition Qs is stronger than one given by a precondition Pt and a postcondition Qt (formally: (Ps, Qs) ⇒ (Pt, Qt)) if Ps is weaker than Pt (i.e. Pt implies Ps) and Qs is stronger than Qt (i.e. Qs implies Qt).

For example, consider the (very weak) specification for a method that computes the absolute value of an argument x, that specifies a precondition 0 ≤ x and a postcondition 0 ≤ result.

This specification says the method need not support negative values for x, and it need only ensure the result is nonnegative as well.

[2][3] Consider a specification for the absolute value method that specifies a precondition 0 ≤ x and a postcondition result = x.

In an influential keynote address[4] on data abstraction and class hierarchies at the OOPSLA 1987 programming language research conference, Barbara Liskov said the following: "What is wanted here is something like the following substitution property: If for each object

Firstly, in its original formulation, it is too strong: we rarely want the behavior of a subclass to be identical to that of its superclass; substituting a subclass object for a superclass object is often done with the intent to change the program's behavior, albeit, if behavioral subtyping is respected, in a way that maintains the program's desirable properties.

In an interview in 2016, Liskov herself explains that what she presented in her keynote address was an "informal rule", that Jeannette Wing later proposed that they "try to figure out precisely what this means", which led to their joint publication[1] on behavioral subtyping, and indeed that "technically, it's called behavioral subtyping".