Vote Up 0 Vote Down

inheritance conflict in programming

Square is the base class from a programming point of view, because it's more simple than the rectangle. A square has just one "value" for it's lines, while a rectangle has 2 (Rectangle extends Square) and a trapezoid has 4 (Trapezoid extends Rectangle extends Square). But on Square you would have a method "setSide($length)" while on Rectangle you would need "setWidth($length)" and "setHeight($length)". How do you solve that?

If I add those methods in Rectangle class, override setSlide from Square class, you would have a Rectangle class with a public method called setSide? What should such a method do? If your Rectangle's clients doesnt know what a Square is what should they think about $rectangle-> setSide () ?


Vote Up 0 Vote Down
How about using the rhombus as the base class? After all, a square is a rhombus with right angles. Or a rectangle with two equal adjacent sides. But wait, a rhombus is a parallelogram with two equal adjacent sides, so a rectangle is just a parallelogram with right angles. What would be the right inheritance hierarchy?

IMO that's a nice OO modeling problem - sort of solving multiple inheritance in a language which disallows it. Here's my take on it: we're after a hierarchy of geometric shapes, when obviously what we're looking at is just a mechanism for mixing and matching different constraints to produce various shapes.

IMO this allows for a nicer approach: a base shape class, modeled as a set of points (it doesn't have to keep the list of all points it contains, it may just provide a method to tell if a point is or isn't in the set, or you could apply it to a raster and ask it to pick the raster points which are part of the shape), to which you attach constraints, which determine what points are or aren't in the set. A square would then be a rectangle constraint mixed with a rhombus constraint, or vice versa. It wouldn't matter.

You could have a simple constraint: a line segment being part of the shape, with a specified length for each segment. Combining this with a rectangle constraint which just enforces right angles and a rhombus constraint which says all sides must be of equal length gives you a square. Combining two of the exotic constraints with a rectangle constraint gives you a rectangle. Combining two such constraints with a parallelogram constraint which just says that opposite sides must be parallel gives you a parallelogram.

And of course, implementing the constraint solver in an efficient way would be quite an interesting challenge.
flag | link |

Your Answer

Login before answering

Login with facebook