Why should I not use equals with inheritance?

后端 未结 2 452
醉梦人生
醉梦人生 2020-12-28 21:26

When I read a Java book, author has said that, when designing a class, it\'s typically unsafe to use equals() with inheritance. For example:

pu         


        
2条回答
  •  無奈伤痛
    2020-12-28 21:57

    Martin Odersky (the guy behind generics in Java and the original codebase for the current javac) has a nice chapter in his book Programming in Scala addressing this problem. He suggests that adding a canEqual method can fix the equality/inheritance problem. You can read the discussion in the first edition of his book, which is available online:

    Chapter 28 of Programming in Scala, First Edition: Object Equality

    The book is of course referring to Scala, but the same ideas apply to classic Java. The sample source code shouldn't be too difficult for someone coming from a Java background to understand.

    Edit:

    It looks like Odersky published an article on the same concept in Java back in 2009, and it's available on the same website:

    How to Write an Equality Method in Java

    I really don't think trying to summarize the article in this answer would do it justice. It covers the topic of object equality in depth, from common mistakes made in equality implementations to a full discussion of Java equals as an equivalence relation. You should really just read it.

提交回复
热议问题