子类equals方法的问题

cqulyk 2016-09-26 05:13:36
我现在有一个父类Point
package org.lyk.entities;


public class Point
{
private int x;
private int y;

public Point(int x, int y)
{
this.x = x;
this.y = y;
}

@Override
public boolean equals(Object obj)
{
if(obj==null)
return false;
if(this == obj)
return true;

if(!(obj instanceof Point))
return false;

Point point = (Point)obj;
if(this.x == point.x && this.y == point.y)
return true;
else
return false;
}
}

现在有一个子类ColoredPoint继承类该父类
package org.lyk.entities;

public class ColoredPoint extends Point
{
private String color;

public ColoredPoint(int x, int y,String color)
{
super(x, y);
this.color = color;
// TODO Auto-generated constructor stub
}

@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
ColoredPoint other = (ColoredPoint) obj;
if (color == null)
{
if (other.color != null)
return false;
} else if (!color.equals(other.color))
return false;


return true;
}


}


主程序代码:
package org.lyk.main;


import java.util.HashSet;

import org.lyk.entities.*;

public class Main
{
public static void main(String[] args)
{
Point p = new Point(1, 2);
ColoredPoint cp1 = new ColoredPoint(1, 2, "RED");
ColoredPoint cp2 = new ColoredPoint(3, 2, "RED");
System.out.println(cp1.equals(cp2));
}
}


我的问题是,子类中的equals只写了新增属性color的比较,没有写父类的x,y的比较。但运行结果是false。我通过在父类equals中加入debug信息,显示在子类做equals比较的时候调用了父类的equals方法的。
那么
1)这个规则是不是JAVA的一个默认规则?
2)我们在重写equals方法的时候是不是只用关心子类字段,不用去考虑父类字段?

提前感谢大家的帮助!
...全文
157 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
inrtyx 2016-09-26
  • 打赏
  • 举报
回复
1.楼上已回答。 2.是的
cqulyk 2016-09-26
  • 打赏
  • 举报
回复
嗨。 我用的自动生成的代码。没注意看~ 太粗心了。
_南天北落 2016-09-26
  • 打赏
  • 举报
回复
你定义子对象就能用了。没必要在父类中写啊。 你可以看看 设计模式中的模版模式。 模版模式
bichir 2016-09-26
  • 打赏
  • 举报
回复
if (!super.equals(obj)) return false; 程序会在这里返回false,, 这里调用了父类的exquels

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧