在Java中重写equals时,为什么使用Object以外的参数不起作用? [英] When overriding equals in Java, why does it not work to use a parameter other than Object?

查看:144
本文介绍了在Java中重写equals时,为什么使用Object以外的参数不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了一个有趣的行为。似乎如果我重写.equals()来获取除Object之外的参数,它就不会被调用。任何人都可以向我解释为什么会这样吗?这似乎违反了我对OOP中多态性的理解,但也许我错过了一些东西。

I ran into an interesting behavior recently. It seems that if I override .equals() to take a parameter other than Object, it doesn't get called. Can anyone explain to me why this is happening? It seems to violate my understanding of polymorphism in OOP, but maybe I'm missing something.

这里有更简单的代码,显示了我所看到的内容:

Here's much simpler code that shows what I'm seeing:

public class MyClass {
  private int x;
  public MyClass(int n) { x = n; }
  public boolean equals(Object o) { return false; }
  public boolean equals(MyClass mc) { return x == mc.x; }
  public static void main(String[] args) {
    List<MyClass> list = new ArrayList<MyClass>();
    list.add(new MyClass(3));
    System.out.println("Contains 3? " + list.contains(new MyClass(3)));
  }
}

运行此功能时,会打印包含3?false 。看起来调用equals(Object)函数,即使有另一个函数可以工作。相比之下,如果我写这样的等于代码按预期工作:

When this is run, it prints "Contains 3? false". It looks like the equals(Object) function is called, even though there is another that would work. By contrast, if I write equals like this the code works as expected:

public boolean equals(Object o) {
  if(!(o instanceof MyClass))
    return false;
  MyClass mc = (MyClass)o;
  return x == mc.x;
}

为什么不弄清楚要调用哪个版本的函数参数的类型?

Why isn't it figuring out which version of the function to call based on the type of the parameter?

推荐答案

你混淆了覆盖和重载。

覆盖 - 为了多态而添加现有方法的替换定义。该方法必须具有相同的签名。签名由名称和参数类型组成。根据目标对象的运行时类型在运行时选择重写方法。

Overriding -- adding a replacement definition of an existing method for purposes of polymorphism. The method must have the same signature. The signature consists of the name and argument types. Overridden methods are selected at runtime based on the runtime type of the target object.

重载 - 添加具有相同名称但具有不同签名的方法。根据目标对象的编译时类型,在编译时选择重载方法。

Overloading -- adding a method with the same name but a different signature. Overloaded methods are selected at compile time based on the compile time type of the target object.

这篇关于在Java中重写equals时,为什么使用Object以外的参数不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆