Type variance is often mentioned in the context of generic types, but it is also applicable when talking about subtyping of classes. From what I have learnt about variance and subtyping, it seems like the following must be true:
If class B
is a subclass of class A
, then methods defined for class B
must take arguments which are supertypes of the arguments taken by the corresponding methods in class A
(if the methods are defined for A
).
At the same time, a common notion in OOP is that a method is merely a function which takes an object of the class as one of its arguments, albeit usually in a syntactically obscured way.
This means, that the methods of the subclass do not only take supertypes as arguments, at least not in this shallow understanding.
My theory is that you could say that a method used in subtyping and polymorphism is slightly more than a simple function. It feels like, in C++ terms, the virtual method on its own is a function which takes an object of the superclass and, using virtual dispatch, returns a function object with the class object captured, which now has the appropriate type (a function type which takes supertypes and returns subtypes, because it no longer takes the object as one of its arguments).
I do not know if this image is a fair representation of reality, though. I am looking for two things:
- The truth, i.e. confirmation that my imagination is correct or the actual theory behind this problem, and
- A citable source which states the truth.
I've seen this post which touches on the problem in the question, but then the answers and comments focus heavily on behavioural subtyping, when I suppose I am more interested in type-theoretic subtyping.