Anonymous user
Define a primitive data type: Difference between revisions
→{{header|Java}}: Grammar fix, added convenience add and assign methods, simplified checkBounds
m (omit TI-BASIC) |
(→{{header|Java}}: Grammar fix, added convenience add and assign methods, simplified checkBounds) |
||
Line 503:
=={{header|Java}}==
The closest you can get to defining a primitive type in Java is making a new wrapper class
This example class throws an exception if the value is out of the bounds; it is implemented only in the assignment
<lang java>class BoundedIntOutOfBoundsException extends Exception
Line 524:
}
private boolean
return true;▼
}▼
}
public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{
assign(i.value()); //could still throw Exception if the other BoundedInt has different bounds
public void assign(int v) throws BoundedIntOutOfBoundsException {
if (
this.value = v;
} else {
throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);
}
▲ }
public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {
}
public int add(int i) throws BoundedIntOutOfBoundsException {
if (
this.value += i;
} else {
Line 555 ⟶ 559:
public class
public static void main(String[] args) throws BoundedIntOutOfBoundsException {
BoundedInt a = new BoundedInt(1, 10);
|