John Kebab
John Kebab

Reputation: 25

Error when trying to use casting, java

I have this method where I want to be able to determine if two cells are equal, where "equal" means they have the same position. I have written this code where I use both instanceof and casting to make sure that my object is of the type Position and then cast it to the type Position, but it does not seem to work for some reason.

Here is my code:

public class Postion {

    private int column;
    private int row;

    public Position (final int column, final int row)  {
        this.column = column;
        this.row = row;
    }

    public int getColumn() {
        return column;
    }

    public int getRow() {
        return row;
    }

    public boolean equals(final Object other) {
        if (other instanceof Position) {
            Position position = (Position) other;
            return ((column == other.getColumn()) && (row == other.getRow()));
        } else {
            return false;
        }
    }
}

I get this error code, in fact I get an error code for both of the get methods:

error:
cannot find symbol
return ((column == other.getColumn()) && (row == other.getRow()));
^
symbol: method getRow()
location: variable other of type Object

Upvotes: 1

Views: 106

Answers (3)

AlexWien
AlexWien

Reputation: 28727

You should rename

Position position = (Position) other;

to

Position otherPos = (Position) other;

then use

otherPos.getColumn()

Upvotes: 0

CodeDreamer
CodeDreamer

Reputation: 444

You used the Object other instead of the typed Position object position.

Upvotes: 1

kosa
kosa

Reputation: 66637

return ((column == other.getColumn()) && (row == other.getRow()));

should be

return ((column == position.getColumn()) && (row == position.getRow()));

Object doesn't contain getColumn() and getRow() methods, it is position, so you need to use position there.

Upvotes: 7

Related Questions