Does Liskov Substitution Principle also apply to classes implementing an interface?

戏子无情 提交于 2020-02-03 11:00:22

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/12921465/does-liskov-substitution-principle-also-apply-to-classes-implementing-an-interfa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!