复合优先于继承(重写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);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值