views:

210

answers:

2

if i have something like

class square : figure {}

class triangle : figure {}

does that mean that i should never ever use the square and triangle classes but only refer to figure ?

like never do like this:

var x = new square();
+4  A: 

In your case, LSP would mean that all behavior inherited from figure should be appropriate for a square or triangle. So you wouldn't want to have setters for figure.Side1, Side2 and Side3 because those wouldn't make sense for a square.

At some point you'll have to refer to square or triangle, but only in cases where what you're doing is specific to the subclass. If you're implementing behavior that will apply equally well for all figures (maybe a Draw method), then it should accept a figure parameter rather than a square or triangle.

As an example, your classes might be set up as follows:

abstract class figure
{
    abstract void draw();
}

class triangle : figure
{
    void draw()
    {
        // ...
    }
}

class drawer
{
    void call_draw(figure fig)
    {
        fig.draw();
    }
}

As long as figure.draw() is virtual, meaning its implementation can (or must) be overriden by a subclass, you can execute triangle's draw() behavior even if the object is being used as a figure.

dahlbyk
how would you draw the triangle, if you don't know that it's a triangle
Omu
You let it draw itself.
wds
rather than "drawing" (which invokes notions of GDI or something tricky) think about GetArea() or GetPerimeter() which exist across all figures.The very key point to pick up is Keith's first paragraph where he talks about Side1 and Side1 which don't make sense for Square. Or consider a circle, which has no sides. If circle inherits from figure. var myCircle = new Circle();myCircle.Side1 = xx; <==== doesn't make any sense in the real world
A: 

You have to define the square and triangle classes and implement their methods - and you have to be able to construct them, as you have indicated:

var x = new square();

Most, if not all other uses of square and triangle should be through the base class figure.

As to LSP, this refers to other methods in other classes which take figure as a parameter:

other_method(figure fig);

This method should be happy about working, whether in fact a square or a triangle instance is passed to it, and it should not have to try to discover the actual class in order to work.

quamrana