[英]Override equals method in java
Let's consider the following simple class. 让我们考虑以下简单的类。
class Point {
private float x;
private float y;
public Point(float x, float y){
this.x=x;
this.y=y;
}
public float getX(){return this.x;}
public float getY(){return this.y;}
public void setX(float x){this.x=x;}
public void setY(float y){this.y=y;}
@Override
public String toString(){
return ("x = "+this.x+", y = "+this.y+";");
}
@Override
public Point clone(){
return new Point(this.x,this.y);
}
@Override
public boolean equals(Object object){
if (object != null && object.getClass()==Point.class){
return object.getX()==this.x && object.getY()==this.y;
}
else{
return false;
}
}
The problem is in the rewrite of method equals: i use the general Object class as attribute to make it more flexible, but netbeans prints error on return line: "Object has no method getX" wich is perfectly logical. 问题在于方法的重写:我使用通用的Object类作为属性使其更灵活,但是netbeans在返回行上打印错误:“对象没有方法getX”是完全合乎逻辑的。
But the problem is still here, how can i manage to fix this ? 但是问题仍然存在,我该如何解决呢?
Thanks you in advance :) 预先感谢您:)
This is pretty simple but you need to cast object
: 这很简单,但是您需要转换object
:
@Override
public boolean equals(Object object){
if (object != null && object.getClass()==Point.class){
Point p = (Point)object;
return p.getX()==this.x && p.getY()==this.y;
}
else{
return false;
}
}
This is also relevant: Casting in equals method 这也很重要: 以equals方法强制转换
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.