Question

LSP states that classes should be substitutable for their base classes, meaning that derived and base classes should be semantically equivalent.

But does LSP also apply to classes implementing an interface? In other words, if an interface method implemented by a class is semantically different from what user expects it to be, would this be considered as a violation of LSP?

Thank you

Was it helpful?

Solution

No

It only applies to subtypes. See the Wikipedia article for a brief summary.

If you have a class B that inherits or extends class A you should be able to switch out class A with class B and everything should work as normal. Interfaces are often used in languages that do not allow for multiple inheritance, so while the two objects share a common behaviour, how that actually execute said behaviour is distinct between both, meaning you shouldn't be able to switch them interchangeably.

OTHER TIPS

Yes. Interfaces have an "is an [noun]" relationship just like classes, except that the noun is not a concrete type, but rather a "thing which is [adjective phrase]". If the adjective phrase is "capable of being safely asked if it can accept items, and either capable of accepting items or reporting that it won't", then any object which could not safely be asked if it could accept items, or which might answer yes but then behave badly if actually given an item, would not be a legitimate implementation of the interface described thereby.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top