我是
Java的初学者.为了训练目的,我正在尝试为自己建立一个国际象棋游戏应用程序.在我的班级Case中,这将用于实现我的所有64个案例,我编写get / set方法来查找案例实例中是否有一个Piece占用者.
我读到返回“null”是一种不好的做法,所以我抛出异常来表示案件是免费的.但是,我想知道如何将占用者的指针设置为“null”;我可以简单地将“null”作为参数调用此方法吗?
此外,可以采取/返回“null”是一个可接受/良好的做法?
public Piece getOccupant(){
if (this.occupant == null)
throw new IllegalArgumentException(this.occupant + " is Empty");
return this.occupant;
}
public void setOccupant(Piece newOccupant){
this.occupant = newOccupant;
}
谢谢!
[更新]
感谢您的所有意见,想法,更正和建议.以下是此部分代码的更新版本,我对此感到满意,因为它有助于实现其目的(通过实践增加我的理解).
/*
* Modifiers of Occupant
*/
/**
* Used to find if a Piece is located in this Cell
* @return a Piece reference to the occupant. Will send a
* null pointer if cell is empty
*/
public Piece getOccupant(){
return this.occupant;
}
/**
* Used to set a new occupant in the Cell.
* @param newOccupant is a reference to a Piece instance,
* and should be set to null if the cell is emptied, or using
* the method clear().
*/
public void setOccupant(Piece newOccupant){
this.occupant = newOccupant;
}
/**
* Used to verify if a Cell is empty of any occupant
* @return true if cell is empty.
*/
public boolean isEmpty(){
if(this.occupant == null)
return true;
return false;
}
/**
* Free the cell of any occupant, if any were
*/
public void clear(){
this.occupant = null;
}