I have a simple base class, which is later extended by many separate classes, which potentially introduce new fields, but not necessarily. I defined an equals method in the
I guess, That's perfect to provide the equals(Object obj)
and hashCode()
method implementation in super
class
as Java
did. We all know that Java provide the hashCode() and equals(Object obj)
method implementation in the base class java.lang.Object, and when ever required we override
them in our class
.
While the following doesn't handle every case, I've found it to be quite practical. I've used this many times when I have both a SuperClass and a SubClass in play. I don't want to inter-compare them, but I also don't want to re-implement all of SuperClass equals() for SubClass. It handles:
Code example
// implement both strict and asymmetric equality
class SuperClass {
public int f1;
public boolean looseEquals(Object o) {
if (!(o instanceof SuperClass)) return false;
SuperClass other = (SuperClass)o;
return f1 == other.f1;
}
@Override public boolean equals(Object o) {
return looseEquals(o) && this.getClass() == o.getClass();
}
}
class SubClass extends SuperClass {
public int f2;
@Override public boolean looseEquals(Object o) {
if (!super.looseEquals(o)) return false;
if (!(o instanceof SubClass)) return false;
SubClass other = (SubClass)o;
return f2 == other.f2;
}
// no need to override equals()
}