I'm overriding the equals(Object o) method of an Object that is identified by an string:
class User {
@Override
public boolean equals(Object o) {
return o != null && o.hashCode() == this.hashCode();
}
@Override
public int hashCode() {
return id.hashCode();
}
}
But I'd like to check also if o
is a subclass of this
or vice versa before returning true in the method equals()
for the first case I can use if (o instance of User)
but how can I make the check in the other way?
Thanks
Edit: Since I've not explained it correctly I'm going to explain the complete problem:
I have the class
public abstract class UniqueIdentifiedObject<E> {
private E id;
protected UniqueIdentifiedObject(E id) {
super();
this.id = id;
}
public E getId() {
return id;
}
@Override
public boolean equals(Object o) {
return o != null && o.hashCode() == this.hashCode();
}
@Override
public int hashCode() {
return id.hashCode();
}
}
and the idea is to inherit this class with an object when it is unique identified by a element: For example if the Users of my app are identified by a integer i'll use:
class User extends UniqueIdentifiedObject<Integer>
and for the Movies
class Movie extends UniqueIdentifiedObject<Integer>
The problem with this implementation of UniqueIdentifiedObject is that if call equals()
with the movie with id = 1 and the user with the id=1 it will return true.
How can I solve this?