Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call a method of a custom class on a parameter of Object class?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading