JAVA画限制范围的函数图像,Java类构造函数具有范围限制的参数

I'm new to Java and I'm asking this question just to help me better understand OOP.

Let's say I'm defining a new Class called Hour. To instantiate this Class, we need to specify an integer to indicate the hour of this instance.

Hour hr = new Hour(16); // this means to define an hour that indicates 4pm.

So when we define the Hour Class here, the parameter for the constructor should within the range [0, 24). How can we define such a parameter and can I throw an error when a parameter that is out of this range is specified?

Thanks.

解决方案

If you would like the compiler to catch the error, you could define an enum for the hours, then use that as the parameter of the constructor of Hour. This might make the Hour class useless, though.

public class Hours {

_1, _2, _3, // etc.

}

public class Hour {

public Hour(Hours hour) { // no need for runtime check here, can not be wrong}

}

Hour hour = new Hour(Hours._3);

This technique may not be the best here, but generally it is better to rely on compile time checks than on runtime ones.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值