tags:

views:

69

answers:

3

Hello,
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.

+2  A: 

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.

Tom Tresansky
Tom, thanks .. Yes that is my question.. not about the implementation... I wasn't sure how JPA handles abstract classes.. a quick search show some examples of specifying DiscriminatorColumn too.. I will read more..
bsreekanth
@bsreekanth, when u don't specifically override equals in A, equals() and hashCode() is inherited from Object.
aberrant80
A: 

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.

aberrant80
thanks.. sorry being not clear with my question, but u guessed me right :-)
bsreekanth
+1  A: 

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.

atamanroman