-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathLiskovSubstitutionPrinciple.java
53 lines (44 loc) · 1.33 KB
/
LiskovSubstitutionPrinciple.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
package good_practices;
import org.junit.Test;
/**
* Created by pabloperezgarcia on 01/03/2017.
*
* As per the LSP, derived classes must be substitutable for the base class
* In this case Square which extends Rectangle must be possible be reference as rectangle
* and continue working.
*/
public class LiskovSubstitutionPrinciple {
class Rectangle {
private int length;
private int breadth;
Rectangle(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}
int getArea() {
return this.length * this.breadth;
}
}
/**
* Square class; Square inherits from Rectangle;
* Represents ISA relationship - Square is constantClass Rectangle
*
*/
public class Square extends Rectangle {
Square(int length, int breadth) {
super(length, breadth);
}
}
@Test
public void calcAreaTest() {
assert calculateArea(new Rectangle(2, 4)) == 8 : "Error";
assert calculateArea(new Square(2, 2)) == 4 : "Error";
}
/**
* calculate area method prove the LSP since it´s receiving just rectangles but we manage to pass constantClass
* square and works as constantClass rectangle
*/
private int calculateArea(Rectangle r) {
return r.getArea();
}
}