-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathCovariantEquals.java
More file actions
41 lines (34 loc) · 887 Bytes
/
CovariantEquals.java
File metadata and controls
41 lines (34 loc) · 887 Bytes
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
class BadPoint {
int x;
int y;
BadPoint(int x, int y) {
this.x = x;
this.y = y;
}
// overloaded equals method -- should be avoided
public boolean equals(BadPoint q) {
return x == q.x && y == q.y;
}
}
BadPoint p = new BadPoint(1, 2);
Object q = new BadPoint(1, 2);
boolean badEquals = p.equals(q); // evaluates to false
class GoodPoint {
int x;
int y;
GoodPoint(int x, int y) {
this.x = x;
this.y = y;
}
// correctly overrides Object.equals(Object)
public boolean equals(Object obj) {
if (obj != null && getClass() == obj.getClass()) {
GoodPoint q = (GoodPoint)obj;
return x == q.x && y == q.y;
}
return false;
}
}
GoodPoint r = new GoodPoint(1, 2);
Object s = new GoodPoint(1, 2);
boolean goodEquals = r.equals(s); // evaluates to true