Reputation: 58712
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.
Upvotes: 1
Views: 3149
Reputation: 11818
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.
Are you asking for polymorphism? If you do: yes, which method gets called depends on the runtime type, not the type of the reference. As long as your objects are typeof B or C everything is fine.
Upvotes: 1
Reputation: 13017
I think your example code is incomplete because I suspect you're asking that if the d.equals()
method uses a.equals()
, then which version of the equals()
method gets called?
If that's what you're asking, then the answer would be the equals()
method of the type of a
. If a
is a B
, then the B.equals()
will get called. If a
is a C
, then C.equals()
gets called. This is true regardless of whether A
has its own implementation of the equals()
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 A
directly, which should really be abstract anyway, since that's how you described it.
Upvotes: 0
Reputation: 19877
Are you asking if it is ok to write hashcode and equals methods in a derived class where the immediate superclass doesn't have them implemented?
If you say class A would never be instantiated directly, why not declare A abstract, then there will be no problem.
Upvotes: 2