简体   繁体   中英

2 Mutable variables in Superclass 1 Unique id on Subclass. How best to override the equals and hashcode methods

I have a Superclass with int a and int b. These variables are mutable. This superclass has 2 methods that can change the values of int a and int b for any object instances created from it.

I have a subclass inherited from the Superclass (extends) and also overrides the 2 superclass methods to add improved functionality that was lacking in the superclass.The subclass has 1 instance variable that is a unique id. I wanted to show the overriding of the equals and hashcode method for both the Superclass and subclass. It probable does not need to be done but I was wanting to overide the equals and hashcode for one or both classes to suit my situation.

The superclass does not have a unique id instance variable. The superclass objects are unique and I wanted to show this in the equals and hashcode methods by comparing superclass int a and int b with instance of superclass int a and int b. Is this feasible? I did not want to use the default equals method which compares equality using the memory reference for two objects being compared.

I also wanted to show objects of the Subclass using Int c (unique id), int a and int b as unique in the equals method.

can I do equality checks in both superclass equals and subclass equals methods, or is is a bit pointless? I did not want to use the default memory reference check but wanted to show equality or uniqueness using my 2 mutable int variables (superclass) and 1 unique id (subclass)

Do I or can I still need to test for equality if I override superclass equals and subclass equals knowing that the equality rules are broken?

Can I just override the supclass equals and hashcode methods, would that be best for my situation?

Any help much appreciated

There are basically two different philosophies here:

a) sub extends super, so sub.equals() and sub.hashCode() both delegate to super.equals() and super.hashCode()

b) each class is responsible for it's own contract enforcements, sub.equals() and sub.hashCode() will consider parent fields by referencing them through the getters ( super.getXyz() ).

Both of these approaches are valid. In approach a), super.equals() will check for instanceof compatibilty, in approach b) super.equals() will compare this.getClass() to that.getClass() . The problem with approach a) is that it will give you asymmetric equals() comparisons. In some cases sub.equals(super) will be false, but super.equals(sub) will be true.

Read items 8 and 9 of Effective Java for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM