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

例のように関数をオーバーロードし、オブジェクトを通常どおりインスタンス化する場合、someClassをequals関数に指定すると、SomeClassをパラメーターとして持つequals関数が呼び出されます。その他のクラスの場合、パラメーターとしてObjectを使用するequals関数が呼び出されます。

ただし、オブジェクトを親クラスとしてインスタンス化する場合、動作は異なります。これは動的バインディングと関係があります。これはここで非常によく説明されています:Javaのオーバーロードと動的バインディングに関する質問

オブジェクトがSomeClassタイプの場合に何か他のことをしようとしている場合はinstanceof SomeClass、標準のequals関数でも使用できることに注意してください。(議論を始めようとはしていませんが、それはオプションです)

于 2012-12-15T15:15:26.203 に答える
1

パラメータまたはのサブクラスをpublic boolean equals(SomeClass s)使用して呼び出すと、が呼び出されます。SomeClassSomeClass

他のオブジェクトでは、それがpublic boolean equals(Object o)呼び出されます。

ただし、他のAPIでメソッドが呼び出されている場合は、が呼び出されますpublic boolean equals(Object o)。これは誤った動作につながります。JavaコレクションAPIはその一例です。

したがって、このようにequalsメソッドをオーバーロードしないでください。

于 2012-12-15T15:22:53.227 に答える