3.2. Subranges.   

We have seen integer= -Integer.MAX_VALUE to Integer.MAX_VALUE.
We may only want a small range of this : posint = 1 .. Integer.MAX_VALUE EX:


type less = 1..31
var j:less
i:integer
begin
j 34 // compile error - not in range
i 34 // OK
j i // OK at compile
end // Run time error - Scalar out of range

Surely these two are of different types? i is of type integer and j is of type 1..31 !

Very nearly the same!!
Contention as to whether the assignment should be picked
up as a compile time error or not.

We could create a new type in Java via the class mechanism:

   class IntegerSubRange

{
// First the data and the constructor
// of this class
private int
lowerBound;
private int upperBound;
private int value;
public IntegerSubRange(int lower, int upper)
{
lowerBound=lower;
upperBound=upper;
}

  // methods for manipulating value indirectly.

public assignValue(int val)
{
if ( (val >=lowerBound) &&
(val <=upperBound) )
value = val;
else /* error */;
}
public int returnValue()
{
return(value);
}
} // end of class with data and methods.
and declare variable as:
IntegerSubRange j =
new IntegerSubRange(lower,upper);

Now we can ONLY use or look at the IntegerSubRange value via the methods - the actual value is private and we cannot see it via j.value. The value has been hidden - we have data hiding.

What should we do with the error? What kind of thing can we do?

     public assignValue(int val) throws IllegalAccessException

{
if ( (val >=lowerBound) && (val <=upperBound) )
value = val;
else
throw new IllegalAccessException(
"Assigned value must be between " + lowerBound + " and " + upperbound + "inclusive");
}

3.2.1. Subranges of defined types.   

We can use subranges of user defined or enumerated types as below:


type colour = (red,orange,yellow,green,blue,indigo,violet);
roy = red .. yellow;
gbiv = green .. violet;
roygb = red .. blue;
workday = monday..friday;
Must define type before using