right way to incorporate superclass into a Guava Objects.hashcode() implementation?

前端 未结 3 1084
别跟我提以往
别跟我提以往 2021-02-12 10:44

Possibly a dumb question, but I don\'t want to screw this up. Let\'s say I have two Java classes, Class1 and Class2, where Class2 extends Class1

3条回答
  •  南方客
    南方客 (楼主)
    2021-02-12 11:25

    Effective Java does address this situation...by saying that you shouldn't do it. Item 8:

    It turns out that this is a fundamental problem of equivalence relations in object-oriented languages. There is no way to extend an instantiable class and add a value component while preserving the equals contract, unless you are willing to forgo the benefits of object-oriented abstraction.

    (Corollary: the same reasoning applies to hashCode().)

提交回复
热议问题