Liskov replacement principle - How to model a square and a rectangle

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?

+5
source share
5 answers

If you make the square and rectangle immutable, then you will not violate the LSP.

, , - , , .

+12

:

- . : . , .

, , . , LSP, , .

+1

(bool square ), (x, y, w, h?) "", .

, , "", , . set(x, y, w, h) , IllegalArgumentException , .

0

, , 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.

0

: ,

, , . . , Rectangle, . , Rectangle, Square.

. , . , . . , Rectangle Square, , . , .

: - meh. , , , . , , . , , , , .

0

All Articles