Reputation: 219
I have a question regarding how a child class inherits from another child class which inherits from the base class. Consider the following: Triangle inherits from Shape, and RightTriangle inherits from Triangle. I have an image below to describe the scenario.
Can it be possible for RightTriangle to inherit directly from Shape (Given that it is also a shape)?
Upvotes: 1
Views: 738
Reputation: 109005
"It depends".
If the types are immutable, where "modifying" operations return a new instance then this could work.
But if there are mutating operations then it will not.
Consider:
Rectangle rect = new Square(10); // Sides of length...
rect.SetWidth(20);
Does that mean rect
is no longer a square, does it throw, or does it set the height as well? All three results are bad (and violate Liskov).
In the immutable case rect.SetWidth
would return a new instance, each subtype would need to be written with logic to handle switching types when required (eg. in the above rect.SetWidth(10)
could return a Square
because the sides remain the same length).
While geometrically the hierarchy works, that is because in geometry all operations create new shapes and you then look at the properties of the new shape to classify it. In a statically typed language with mutable objects neither of those restrictions applies.
Upvotes: 2
Reputation: 17003
Part I:
Can it be possible for RightTriangle to inherit directly from Shape
Yes,
if RightTriangle does not inherit from Traingle
No,
If RightTriangle inherit from Traingle --> C# Does not support multi inheritance -> compile error
Part II:
Given that it is also a shape
Same here if RightTriangle inherit from Shape then you can cast it as a Shape.
Upvotes: 1