3 ms·
Subclasses get narrower (that is, more specific) than their parents. Consider those constructors. In order to constructor-chain from a Square up to a Rectangle,
by chrisoverzero 6y ago
Subclasses get narrower (that is, more specific) than their parents. Consider those constructors. In order to constructor-chain from a Square up to a Rectangle, duplicate the single parameter:
Square(side) : Rectangle(side, side)
There's not a well-behaved way to go in the other direction.
Rectangle(width, height) : Square(width) // ???
Rectangle(width, height) : Square(height) // ???
- pdpi 6y ago> Subclasses get narrower (that is, more specific) than their parents. That's precisely the problem. Subclasses have to less restrictive than their parents. If a subclass adds observable restrictions, it fails the LSP.
- Twisol 6y agoConversely, if a subclass adds observable flexibility -- such as the ability to stretch along a single axis -- it also fails the LSP. Subclasses can really only add orthogonal properties, such that influencing one of these properties doesn't perturb properties observable from the super-interface.
- BeetleB 6y ago> Conversely, if a subclass adds observable flexibility -- such as the ability to stretch along a single axis -- it also fails the LSP. That's not a given. If the new capability is only in new methods of the subclass, then the program expecting the parent class will never be impacted by it. To be fair, I suppose you agree: > such that influencing one of these properties doesn't perturb properties observable from the super-interface.
- Twisol 6y agoRight, that's why I qualified both times with "observable". ~_^ It's worth noting that even if this capability can only occur due to methods on the subclass alone, it can still fail LSP if those manipulations are still observable to a client using only the superclass. This is pretty much only possible because multiple clients can have a reference to the same object, since it allows one client to observably transition the object into a state that should be unreachable from the perspective of the second client. (This is the root of the need to make "defensive copies" [1].) If one imposes a strict single-ownership discipline, then it doesn't matter if super-interface properties can be violated by subclass-only methods, because for the duration of its use via its super-interface, those violations are impossible (and hence unobservable). [1] http://www.javapractices.com/topic/TopicAction.do?Id=15 http://www.javapractices.com/topic/TopicAction.do?Id=15