Shubhankit Roy
Shubhankit Roy

Reputation: 39

Overriding/Hiding Object class's equals() method in Java

For the following piece of code :

public class Point {

    private int xPos, yPos;

    public Point(int x, int y) {
        xPos = x;
        yPos = y;
    }

    // override the equals method to perform
    // "deep" comparison of two Point objects
    public boolean equals(Point other) {
        if (other == null)
            return false;
        // two points are equal only if their x and y positions are equal
        if ((xPos == other.xPos) && (yPos == other.yPos))
            return true;
        else
            return false;
    }

    public static void main(String[] args) {
        Object p1 = new Point(10, 20);
        Object p2 = new Point(50, 100);
        Object p3 = new Point(10, 20);
        System.out.println("p1 equals p2 is " + p1.equals(p2));
        System.out.println("p1 equals p3 is " + p1.equals(p3));
    }
}

The output is :

p1 equals p2 is false
p1 equals p3 is false

I understand that the equals method should have "Object" class's object as an argument. The explanation for the above behavior I got is that here the equals method is hiding (not overriding) the equals() method of the Object class.

I don't understand why is it hiding and not overriding! While overriding equals method, can't we use subclasses' object as an argument to the equals method?

Upvotes: 0

Views: 173

Answers (2)

Yassin Hajaj
Yassin Hajaj

Reputation: 21995

As said by @Eran, you were overloading.

Here is a way to override it :

   @Override
    public boolean equals(Object obj) {
        return obj == null ? false : ((xPos == (Point)obj.xPos) && (yPos == (Point)obj.yPos));
    }

Upvotes: 0

Eran
Eran

Reputation: 393936

It's neither hiding nor overriding. Your equals method overloads Object's equals method (overloading is the term that applies to multiple methods in the same class hierarchy having the same name and different signatures). Overriding requires the overriding method to have the same signature as the method it overrides.

p1.equals(p3) executes Object's equals, since you are executing it on an instance whose static type is Object (as declared in Object p1 = ...).

Upvotes: 4

Related Questions