1

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" which is perfectly logical.

But the problem is still here, how can I manage to fix this?

Thanks you in advance

1

1 Answer 1

3

This is pretty simple but you need to cast 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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.