2012-12-07 66 views
1

我有這種方法,我想能夠確定兩個單元格是否相等,其中「相等」意味着他們有相同的位置。我寫了這段代碼,我使用instanceof和cast來確保我的對象的類型爲Position,然後將它轉換爲類型Position,但由於某種原因它似乎不起作用。錯誤當試圖使用鑄造,java

這裏是我的代碼:

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 

回答

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

應該

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

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

+0

謝謝你們!這確實有助於:) 保持支持'! ;) –

1

您使用了對象而不是類型化的位置對象位置。

0

你應該重新命名

Position position = (Position) other; 

Position otherPos = (Position) other; 

然後用

otherPos.getColumn()