複合優先於繼承(重寫equals方法引出的建議)

摘自effective java
問題: 有一個Point類,重寫了equals方法
public class Point{
private final int x;
private final int y;
public Point(x,y){
this.x=x;
this.y=y;
}
@Override public boolean queals(Object o){
if(!(o instanceof Point){
return false;
}
Point p = (Point)o;
return p.x == x && p.y == y;
}
}
另有一個擴展類,ColorPoint
public class ColorPoint{
private final Color color;
public ColorPoint(int x,int y,Color color){
super(x,y);
this.color=color;
}
}
此時,Point point = new Point(1,2);
ColorPoint cPoint = new ColorPoint(1,2,Red);
point.equals(cPoint) == true;
因爲他的equals方法忽略了顏色的判斷。
此時可修改equals方法:
if(!(o.instanceOf(Point))
return false;
//if o is a normal point,ignore color
if(!(o.instanceOf(ColorPoint))
return o.equals(this);
//if o is a colorPoint .do a full compation
return super.equals(o) && ((ColorPoint)o).equals(this.color);
該方法可以實現兩個點的判斷,但兩個以上的點會有錯誤,比如 兩個ColorPoint和一個Point作比較,如下:
ColorPoint redPoint = new ColorPoint(1,2,Red);
ColorPoint bluePoint = new ColorPoint(1,2,Blue);
Point normalPoint = new Point(1,2);
此時:
redPoint.equals(normalPoint) == true;
bluePoint.equals(normalPoint) == true;
但是
redPoint.equals(bluePoint) == false;
這種情況違反了equals的傳遞性。
這時候有個建議:複合優先於繼承。
public class ColorPoint{
private final Point point;
private final Color color;
public ColorPoint(int x,int y,Color color){
point.x = x;
point.x = x
this.color = color;
}
public Point getPoint(){
return this.point;
}
//重寫equals
@Override public boolean equals(Object o){
if(!(o instanceof ColorPoint){
return false;
}
ColorPoint cp = (ColorPoint)o;
//只有當座標和顏色都相同才返回true;
return cp.point.equals(this.point) && cp.Color.equals(color);
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章