3

Let's say I want to override the method equals() of Object:

    public boolean equals(Object o){
      //something
    }

    public boolean equals(SomeClass s){
      //something else
    }

SomeClass is obviously also an Object, so which method will be called if I use equals with an Instance of SomeClass as parameter?

4

3 回答 3

6

That's not overriding, it's overloading. If you do that you'll end up with two equals methods: one that will be invoked for (subclasees of) SomeClass instances and one for any other objects.

One thing to note is that the method binding will be static: the compiler will decide which one to call based on the declared type of your reference. Therefore, the following will invoke the equals(Object), not equals(SomeClass):

Object o = new SomeClass();
o.equals(o);  // invokes SomeClass.equals(Object)
于 2012-12-15T15:07:36.773 回答
1

当您public boolean equals(SomeClass s)使用参数SomeClassSomeClass.

对于任何其他对象,它都会被public boolean equals(Object o)调用。

但是,当您在其他 API 中调用 equals 方法时,它们将调用public boolean equals(Object o). 这将导致错误的行为。Java 集合 API 就是一个例子。

所以不要像这样重载equals方法。

于 2012-12-15T15:22:53.227 回答
1

如果您像示例中那样重载该函数,并正常实例化该对象,则如果您向 equals 函数提供 SomeClass ,则将调用以 SomeClass 作为参数的 equals 函数。对于任何其他类,将调用以 Object 作为参数的 equals 函数。

但是,如果将对象实例化为父类,则行为会有所不同。这与动态绑定有关,这里解释得很好:关于 Java 重载和动态绑定的问题

请注意,如果您希望在 Object 属于 SomeClass 类型时执行其他操作,您也可以instanceof SomeClass在标准 equals 函数中使用。(不是试图开始讨论,但这是一种选择)

于 2012-12-15T15:15:26.203 回答