Re: Composition vs. inheritance
Ulrich Eckhardt wrote:
I can give you a few examples when it is not appropriate to inherit. One of
the things already started the discussion mentioned above, like e.g.
deriving a square class from a rectangle class. If you do that, you are
simply violating the Liskow(sp?) Substitution Principle, because inherently
expected behaviour of a square is incompatible to that of a rectangle. A
Not necessarily. It's a design issue. If you design Square to inherit
Rectangle according to Liskov, then you'd do something like this:
enum Side { RIGHT, TOP, LEFT, BOTTOM }
interface Rectilinear
{
void setLen( Side s, Integer len );
Integer getArea();
}
class Rectangle implements Rectilinear
// could extend Parallelogram
{
private Integer right, top, left, bottom;
// public getters and setters for these
public void setLen( Side side, Integer len )
{
switch( side )
{
case RIGHT:
case LEFT:
setRight( len );
setLeft( len );
break;
case TOP:
case BOTTOM:
setTop( len );
setBottom( len );
break;
}
}
public Integer getArea()
{
return (right == null || top == null || left == null || bottom == null?
null : right * top);
}
}
class Square extends Rectangle
{
public void setLen( Side side, Integer len )
{
setRight( len );
setLeft( len );
setTop( len );
setBottom( len );
}
}
--
Lew