java 判断返回null_Java – 获取/设置接收和返回“null”的方法

我是

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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值