简体   繁体   中英

Why doesn't this equals method properly override the object.equals method?

public class Person{
    private String name;
    public Person(String name) {
         this.name = name;
    }
    public boolean equals (Person p){
         return p.name.equals(this.name);
    }
}

The equals method does not properly override the object.equals method. Why?

The equals method recieves an Object , not a Person , and should return false for any argument that isn't a Person instance. Eg:

@Override
public boolean equals (Object o) {
     if (!(o instanceof Person)) {
         return false;
     }
     Person p = (Person) o;
     return p.name.equals(this.name);
}

This is because the signature of the equals() method in Object is

public boolean equals(Object o)

Notice the type of the input is Object . Technically an override cannot be of a subtype, it must be of the same type. Your method is an overload instead of an override.

The signature of the equals method is

public boolean equals(Object other);

If you think about it that's because you might want to compare the object to objects of different types.

public boolean equals(Object obj) 

is the syntax

But remember to override the hashcode method as well.

When overriding a method everything should be same as the method which you are trying to override.

In your case equals method is using Person but originally it takes an Object Type.

The overriding method has the same name, number and type of parameters, and return type as the method that it overrides.

Reference: http://docs.oracle.com/javase/tutorial/java/IandI/override.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM