Java Class Constructor Parameters with range limits

前端 未结 3 1564
北恋
北恋 2020-12-21 10:08

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

3条回答
  •  隐瞒了意图╮
    2020-12-21 10:31

    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.

提交回复
热议问题