I have written a class, Statistician, which has a method to check for equality with an object. This method, equals(Object obj), calls another method from the Statistician class, mean(). Below is a simplified version of equals(Object obj) that only checks for equality in one field using mean().
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != Statistician.class) {
return false;
}
if (obj.mean() != this.mean()) {
return false;
}
return true;
}
The problem is that calling mean() on obj is a syntax error. I don’t know how to get around this, as per my assignment I must pass obj as an Object class, and not as a Statistician class.
I have tried compiling the above code and received a syntax error.
>Solution :
Once you’ve done a typecheck, you can cast the object to the correct type confidently.
Statistician statistician = (Statistician)obj;
Then make all future calls on statistician, not obj.
Additionally, you should use instanceof to do the typecheck, not getClass. The latter is for more advanced reflection techniques.
if (!(obj instanceof Statistician)) {
return false;
}
If you ever subclass Statistician, this will still work. Even if Statistician is final, this is still the more readable version than dipping into reflection for something so simply. This has the added side effect of removing the null check, since null is never an instanceof any type.