Possible duplicate:Is a square from a rectangle a violation of the Liskov Substitution Principle?
Using LSP, can anyone give me an implementation of Square and Rectangle?
I read the book "Head First Object-Oriented Analysis and Design", they said that if Sqaure inherits from Rectangle, it violated the LSP, but does not have the correct implementation.
Anyone want a try?
If you make the square and rectangle immutable, then you will not violate the LSP.
, , - , , .
:
- . : . , .
, , . , LSP, , .
(bool square ), (x, y, w, h?) "", .
bool square
, , "", , . set(x, y, w, h) , IllegalArgumentException , .
set(x, y, w, h)
IllegalArgumentException
, , LSP:
public class Rectangle { int width; int height; public Rectangle(int w, int h) { width = w; height = h; } //getWidth(), getHeight, getArea(), etc, but no setters. } public Square extends Rectangle { public Square(int side) { super(side, side); } }
, scale(), , LSP- , grow() , , , , , LSP.
scale()
grow()
: ,
, , . . , Rectangle, . , Rectangle, Square.
. , . , . . , Rectangle Square, , . , .
: - meh. , , , . , , . , , , , .