Q:

How to delimit the range of an instance variable of a class in java?

I am doing some java exercise and trying to figure out a way to impose restrictions on the scope of an instance variable.
For example I constructed a class called Time. It has 3 instance variables, hour, minute and second.
Take hour for example, it should be between 0 to 23. I have some methods inside this class to manipulate the hour variable. But I need to make sure hour is always within 0 to 23.
I know there is a method, enum type. Like this
public enum hour {
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
    21, 22, 23
}

and then insert an hour type variable in Time class.
But what if hour is a double type variable, continuous variable. And it has its upper and lower limit. How do i delimit a continuous variable?

A:

There is no compiler save way to set limits. a possible (and always recommended) way is that you use a private variable and check in the setter method the bounds and throw a RuntimeException if the bounds are not correct.
Example:
public class Time {
    private double hour;

    public void setHour(double hour) {
        if(hour < 0 ) { // and so on - i think you can imagine the logical expression
            throw new IllegalArgumentException("hour "+hour+" is not valid.");
        }
        this.hour = hour;
    }
}

