In "Effective Java 2nd edition", page 40, It says that the getClass-based equals method violates Liskov Substitution Principle. Following is the super-type Point and subtype CounterPoint source code :
Code: Alles auswählen
public class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override public boolean equals(Object o) {
if (o == null || o.getClass() != getClass())
return false;
Point p = (Point) o;
return p.x == x && p.y == y;
}
}
Code: Alles auswählen
public class CounterPoint extends Point {
private static final AtomicInteger counter = new AtomicInteger();
public CounterPoint(int x, int y) {
super(x, y);
counter.incrementAndGet();
}
public int numberCreated() {
return counter.get();
}
}
Regards.