java why should equals method input parameter be Object

后端 未结 6 930
别那么骄傲
别那么骄傲 2020-12-09 10:42

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{
    /         


        
6条回答
  •  情深已故
    2020-12-09 10:59

    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).

提交回复
热议问题