?????Java?б???equals?????????????壨?£?
???????????? ???????[ 2012/9/18 10:13:57 ] ????????
????????????redP??blueP??????false??
System.out.println(redP.equals(blueP)); // ??? false
????????equals????????Υ?????
?????equals??????????????????????????????????ò???????????????????????equals??????????????????????????????????????Point???ColoredPoint???equals??????????????????????????????????????????Point??????Point?????????????????????????????
// A technically valid?? but unsatisfying?? equals method
public class Point {
private final int x;
private final int y;
public Point(int x?? int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override public boolean equals(Object other) {
boolean result = false;
if (other instanceof Point) {
Point that = (Point) other;
result = (this.getX() == that.getX() && this.getY() == that.getY()
&& this.getClass().equals(that.getClass()));
}
return result;
}
@Override public int hashCode() {
return (41 * (41 + getX()) + getY());
}
}
??????????????ColoredPoint???equals????????????????????????equals??????
public class ColoredPoint extends Point { // ????Υ???????????
private final Color color;
public ColoredPoint(int x?? int y?? Color color) {
super(x?? y);
this.color = color;
}
@Override public boolean equals(Object other) {
boolean result = false;
if (other instanceof ColoredPoint) {
ColoredPoint that = (ColoredPoint) other;
result = (this.color.equals(that.color) && super.equals(that));
}
return result;
}
}
????????Point????????е???????????????????????????????????????????????????????????ζ?? .getClass()????????????????????????????????????????????????????????????????????????false???????????(colored point)???????????(point)?????????????????????????????????????????????——?????????????????
???????????????????????????????????????????????(1??2)
Point pAnon = new Point(1?? 1) {
@Override public int getY() {
return 2;
}
};
????pAnon????p???????????p??pAnon??java.lang.Class???????p??Point????pAnon??Point???????????????????????????????pAnon???????????1??2??????????????????????????????????????????
??????
???·???
??????????????????
2023/3/23 14:23:39???д?ò??????????
2023/3/22 16:17:39????????????????????Щ??
2022/6/14 16:14:27??????????????????????????
2021/10/18 15:37:44???????????????
2021/9/17 15:19:29???·???????·
2021/9/14 15:42:25?????????????
2021/5/28 17:25:47??????APP??????????
2021/5/8 17:01:11