尝试使用转换时出错,java

时间:2012-12-07 20:01:37

标签: java casting instanceof

我有这种方法,我希望能够确定两个单元格是否相等,其中“相等”意味着它们具有相同的位置。我编写了这段代码,我同时使用instanceof和强制转换以确保我的对象属于Position类型,然后将其强制转换为类型Position,但它似乎没有出于某种原因工作。

这是我的代码:

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;
        }
    }
}

我收到此错误代码,实际上我得到了两个get方法的错误代码:

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

3 个答案:

答案 0 :(得分:7)

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

应该是

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

对象不包含getColumn()getRow()方法,它是位置,所以你需要在那里使用位置。

答案 1 :(得分:1)

您使用了Object other而不是键入的Position对象位置。

答案 2 :(得分:0)

你应该重命名

Position position = (Position) other;

Position otherPos = (Position) other;

然后使用

otherPos.getColumn()