3 ms·
If you think of a type as a set of possible values, then a subclass is actually a supertype—a superset of the possible values of its parent class—and likewise a
by gngeal 13y ago
If you think of a type as a set of possible values, then a subclass is actually a supertype—a superset of the possible values of its parent class—and likewise a superclass is a subtype.
Nope. A subclass is usually (not always!) a subtype, not the other way round. Or, more specifically (and accurately), most statically-typed class-based OO languages treat subclasses in their type systems as subtypes by default, i.e., they assume that a subclass instance can act as an instance of its superclass, LSP-wise. This, I believe, is as accurate statement as one can make (on this level of generality).
The “is-a” relationship is saying “for all instances I of X, I is an instance of Y” which is essentially the definition of superset. That is what the Liskov Substitution Principle is about.
It's a definition of a superset, if Y is the superset and X is the subset.
In C++ and other languages with support for object-oriented programming, a subclass is not necessarily a supertype: virtual functions can throw “I don’t make sense in this derived class”.
That's a part of why I believe that static typing doesn't make too much sense when it comes to OO languages (with (sub)classes). If static typing is supposed to take care of subtype assignability statically and the semantics of the behaviour of derived classes can break the LSP assumptions, static typing becomes sort of worthless.