What are the consequences of implementing equals() method like this (using getClass() instead of using instanceof)?
public class Point {
@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;
}
}
Answer
Liskov substitution principle is violated. For example, we cannot mix Points and objects of any subclass of Point in collections, because Points and objects of any subclass of Point will never be equal, even if subclassing is NOT adding any value field.
Tags
#bloch-effective-java-2ed #java
Question
What are the consequences of implementing equals() method like this (using getClass() instead of using instanceof)?
public class Point {
@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;
}
}
Answer
?
Tags
#bloch-effective-java-2ed #java
Question
What are the consequences of implementing equals() method like this (using getClass() instead of using instanceof)?
public class Point {
@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;
}
}
Answer
Liskov substitution principle is violated. For example, we cannot mix Points and objects of any subclass of Point in collections, because Points and objects of any subclass of Point will never be equal, even if subclassing is NOT adding any value field.
If you want to change selection, open document below and click on "Move attachment"