Is deriving BinaryTreeNode from GraphNode a violation of Liskov's Substitution Princple

廉价感情. 提交于 2019-12-11 17:53:35

问题


The discussion comes up here:

Changing visibility of method in inherited class

question is: is really "BTNode extends GraphNode" design a violation of Liskov's Substitution Princeple? As an "similar" example it was shown that case: Is deriving square from rectangle a violation of Liskov's Substitution Principle?

but I cannot really see why that is similar. I am very new to design, could someone explain me why (if) that's the case?


回答1:


In Is deriving square from rectangle a violation of Liskov's Substitution Principle?, it basically says that Square cannot inherit from Rectangle because there are things that you can do with Rectangles but not with Squares - setting its width to a different number from its height.

You can't inherit BTNode from GraphNode because according to the original post you linked, GraphNode has a method called addChild. BTNode on the other hand, can only have two children. Inheriting from GraphNode will also inherit the addChild method. This allows you to add multiple children to BTNode, which a BTNode cannot handle.

Therefore, BTNode cannot inherit from GraphNode because there are things that you can do with GraphNodes but not with BTNodes - adding multiple children.

For completeness, here is the Liskov's Substitution principle from Wikipedia

Subtype Requirement: Let ϕ(x) be a property provable about objects x of type T. Then ϕ ( y ) should be true for objects y of type S where S is a subtype of T.

In simple terms,

If you can do action X on type T, you should also be able to do action X on any subclasses of T.



来源:https://stackoverflow.com/questions/45897182/is-deriving-binarytreenode-from-graphnode-a-violation-of-liskovs-substitution-p

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