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?
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 Rectangle
s 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 GraphNode
s but not with BTNode
s - 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.