In my understanding, the below implementation of equal and hashcode are safe as the correct method in derived class would invoke (instead of parent), even if I call it through the parent pointer. Provided the parent is treated as abstract class (uses in JPA – hiberante base class). Please confirm this assumption based on the example below.
@Entity
@Inheritance
class A {
String type;
}
@Entity
class B extends A {
String uniqueName;
.......
@Override
public boolean equals(Object obj) {
..
}
@Override
public int hashCode() {
}
}
@Entity
class C extends A {
String uniqueName;
.......
@Override
public boolean equals(Object obj) {
..
}
@Override
public int hashCode() {
}
}
class D {
A a;
String name;
}
Since A can accept the instance of both B and C, when writing the equal/hash method for D, is it ok with the above implementation (only in B & C, not in A). there would not be a case where A is instantiated directly (new A).
thanks.
I think your example code is incomplete because I suspect you’re asking that if the
d.equals()method usesa.equals(), then which version of theequals()method gets called?If that’s what you’re asking, then the answer would be the
equals()method of the type ofa. Ifais aB, then theB.equals()will get called. Ifais aC, thenC.equals()gets called. This is true regardless of whetherAhas its own implementation of theequals()method or not.Since you mentioned Hibernate, I suppose you’re trying to create a joined-subclass mapping or some such. If you map it correctly, then Hibernate won’t try to instantiate an
Adirectly, which should really be abstract anyway, since that’s how you described it.