I'm trying to override equals method, but I'm getting error
I have two classes one abstract and the inherited class.

public abstract class MyData extends Object
{
    public abstract boolean equals(MyData ohtherData);
}


public class IntData extends MyData
{
    protected int num;

    public IntData (int n)
    {
        this.num = n;
    }
    public boolean setNum(int n)
    {
        if (n<0)
            return false;
        else 
        {
            this.num = n;
            return true;
        }
    }
    @Override
    public boolean equals(MyData otherData) 
    {
        if (otherData == null || this.getClass() != otherData.getClass())
        return false;
        else 
        {
            MyData newData = (MyData) otherData;
            return this.num = newData.num;
        }
    }

}

I have problem with the last line return this.num = newData.num; I'm getting that num for newData can not be resolved or is not a field. Nevetherless, my teacher said that I CAN NOT put protected int num in the abstract class. My teacher checked my code and said that it should work but it doesn't.
Any help would be appreciated.

Recommended Answers

All 3 Replies

By glancing, you are returning nothing... return this.num = newData.num; is just an assignment of this.num... Do you want return this.num == newData.num; instead?

Before going into definition, what does equal mean to you? When you deal with equals() method, it is very tricky because you have to think about what you are comparing. Do you allow inherited class object to be compared? Etc...

Line 32 - need to cast to IntData to access that classes' fields

maybe to late, but you are not really "overriding" the method correctly anyway, the method should accept an instance of the type Object as a parameter, first check whether or not it is an instance of the class you're working in, and only if that returns true, check whether or not it's equal to the instance you're calling it on.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.