java why should equals method input parameter be Object

Viewed 9948

I'm going through a book on data structures. Currently I'm on graphs, and the below code is for the vertex part of the graph.

class Vertex<E>{
    //bunch of methods

    public boolean equals(Object o){
         //some code
    }
}

When I try to implement this equals method my compiler complains about not checking the type of the parameter and just allowing any object to be sent it. It also does seem a bit strange to me why that parameter shouldn't be a Vertex instead of an Object. Is there a reason why the author does this or is this some mistake or antiquated example?

6 Answers

If your method doesn't take an argument of type Object, it isn't overriding the default version of equals but rather overloading it. When this happens, both versions exist and Java decides which one to use based on the variable type (not the actual object type) of the argument. Thus, this program:

public class Thing {

    private int x;

    public Thing(int x) {
        this.x = x;
    }

    public boolean equals(Thing that) {
        return this.x == that.x;
    }

    public static void main(String[] args) {
        Thing a = new Thing(1);
        Thing b = new Thing(1);
        Object c = new Thing(1);
        System.out.println(a.equals(b));
        System.out.println(a.equals(c));
    }

}

confusingly prints true for the first comparison (because b is of type Thing) and false for the second (because c is of type Object, even though it happens to contain a Thing).

Related