Java Class Constructor Parameters with range limits

前端 未结 3 1580
北恋
北恋 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:34

    Unfortunately Java unlike Pascal and other languages does not support range types. You can however use the other techniques.

    The simplest way is to check the value in code.

    class Hour {
        private final int h;
        public Hour(int h) {
            if (h < 0 || h >= 24) {
                throw new IllegalArgumentException("There are only 24 hours");
            }
            this.h = h;
        }
    }
    

    You can also use more sophisticated techniques. Take a look on java Validation API In this case your code will look like:

    class Hour {
        @Max(23)
        @Min(0)
        private final int h;
        public Hour(int h) {
            this.h = h;
        }
    }
    

    But you will have to use one of available implementations of this API and invoke it.

提交回复
热议问题