When overriding equals in Java, why does it not work to use a parameter other than Object?

后端 未结 7 1958
攒了一身酷
攒了一身酷 2020-12-03 18:13

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

7条回答
  •  囚心锁ツ
    2020-12-03 18:16

    Ok let me re-phrase.

    (1)Because the compiler eliminates all information regarding to Generics (erasure, see here), and (2) because you cannot override a method without the exact same signature (equals(Object)), (3) during runtime all objects inside the List are treated as Objects and not as instances of MyClass. Hence, the method that gets called is equals(Object) since this is the one that is been overwritten by your class.

提交回复
热议问题