-
Notifications
You must be signed in to change notification settings - Fork 1
/
LSP.java
103 lines (81 loc) · 2.07 KB
/
LSP.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Liskov Substitution Principle (LSP)
package solidprinciples.lsp;
import org.w3c.dom.css.Rect;
class Rectangle {
protected int width, height;
public Rectangle() {
}
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getArea() { return width*height; }
@Override
public String toString() {
return "Rectangle{" +
"width=" + width +
", height=" + height +
'}';
}
// Detecting a square
public boolean isSquare() {
return width == height;
}
}
class Square extends Rectangle {
public Square() {
}
public Square(int size) {
width = height = size;
}
// LSP violated
@Override
public void setWidth(int width) {
super.setWidth(width);
super.setHeight(width);
}
@Override
public void setHeight(int height) {
super.setWidth(height);
super.setHeight(height);
}
}
// Factory design pattern
class RectangleFactory {
public static Rectangle newRectangle(int width, int height) {
return new Rectangle(width, height);
}
public static Rectangle newSquare(int side){
return new Rectangle(side, side);
}
}
class LSPDemo {
static void useIt(Rectangle r) {
int width = r.getWidth();
r.setHeight(10); // bad setter because it makes sense for a rect but not square
// area = width * 10
System.out.println(
"Expected area of " + (width * 10) +
", got " + r.getArea()
);
}
public static void main(String[] args) {
Rectangle rc = new Rectangle(2,3);
useIt(rc);
Rectangle sq = new Square();
sq.setWidth(5);
useIt(sq); // Expected area of 50, got 100
}
}