Java类构造函数具有范围限制的参数 [英] Java Class Constructor Parameters with range limits

查看:1182
本文介绍了Java类构造函数具有范围限制的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想要定义一个新的类叫小时,这个问题只是为了帮助我更好地理解OOP。 。要实例化这个类,我们需要指定一个整数来表示此实例的小时。

 小时hr = ); //这意味着定义一个小时,表示下午4点。 

因此,当我们在这里定义Hour类时,构造函数的参数应该在[0, 24)。我们如何定义这样的参数,并且当指定超出此范围的参数时可以抛出错误?



感谢。

解决方案

如果您希望编译器捕获错误,您可以为小时定义一个枚举,然后使用它作为参数 Hour 的构造函数。这可能会使 Hour 类无用。

  public class Hours {
_1,_2,_3,//等等。
}

public class Hour {
public Hour(小时小时){//不需要运行时检查这里,不能错了}
}

小时=新小时(Hours._3);

这种技术可能不是最好的,但一般来说更好的依靠编译时检查比在运行时。


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.

这篇关于Java类构造函数具有范围限制的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆