简体   繁体   English

为什么此equals方法不能正确覆盖object.equals方法?

[英]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. equals方法不能正确覆盖object.equals方法。 Why? 为什么?

The equals method recieves an Object , not a Person , and should return false for any argument that isn't a Person instance. equals方法接收Object ,而不是Person ,并且对于不是Person实例的任何参数,应返回false 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 这是因为Object equals()方法的签名是

public boolean equals(Object o)

Notice the type of the input is Object . 注意输入的类型是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 equals方法的签名是

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. 但是请记住也要覆盖hashcode方法。

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. 在您的情况下,equals方法使用的是Person,但最初它采用的是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 参考: http : //docs.oracle.com/javase/tutorial/java/IandI/override.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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