how do I correctly override equals for inheritance in java?

后端 未结 2 1345
南旧
南旧 2021-01-21 03:34

I am using hibernate and id... is used for persistence (which is why it is omitted in comparison). (Also, using google guava helper equals)

HolidayPackageVariant:

<
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-21 03:47

    This is how you should implement data objects: no inheritance allowed, composition only.

    These are immutable objects, but you could want to modify them, so remove final where needed. Also you may remove final from the class definition because Hibernate doesn't support it, but in that case, you should document that these classes are not eligible for inheritance.

    The main advantages are all the ones described in Effective Java plus, in this case, you don't have to manage inheritance through Hibernate which can sometimes be a real pain.

    public final class HolidayPackageVariant {
      private final Integer idHolidayPackageVariant;
      private final HolidayPackage holidayPackage;
      private final String typeHolidayPackage;
    
      ...
    
      @Override
      public boolean equals(Object obj) {
        if (obj == this)
          return true;
        if (!(obj instanceof HolidayPackageVariant))
          return false;
    
        HolidayPackageVariant that = (HolidayPackageVariant) obj;
        return Objects.equal(this.typeHolidayPackage, that.typeHolidayPackage)
            && Objects.equal(this.holidayPackage, that.holidayPackage);
      }
    
      @Override
      public int hashCode() {
        return Objects.hashCode(this.typeHolidayPackage, this.holidayPackage);
      }
    }
    
    public final class FlightHolidayPackageVariant {
      private HolidayPackageVariant holidayPackageVariant;
      private Destination originCity;
    
      ...
    
      public HolidayPackageVariant asHolidayPackageVariant() {
        return this.holidayPackageVariant;
      }
    
      public boolean equals(Object obj) {
        if (obj == this)
          return true;
        if (!(obj instanceof FlightHolidayPackageVariant))
          return false;
    
        FlightHolidayPackageVariant that = (FlightHolidayPackageVariant) obj;
        return Objects.equal(this.holidayPackageVariant, that.holidayPackageVariant)
            && Objects.equal(this.originCity, that.originCity);
      }
    
      @Override
      public int hashCode() {
        return Objects.hashCode(this.holidayPackageVariant, this.originCity);
      }
    }
    

提交回复
热议问题