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();
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();
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
.
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.