Reputation: 842
Say I have a method:
public void method(int i) {
this.value =+ i;
}
How can I restrict i to a value greater than x? I understand this can be done outside the method but I would prefer to condition it in the constructor. Would it be something like:
public void method(int i; i > x){...};
Sorry for not testing this myself, I came up with it as I wrote my query.
Upvotes: 1
Views: 3574
Reputation: 691845
You document the method, and throw an exception if the caller doesn't respect the contract.
/**
* Does something cool.
* @param i a value that must be > x
* @throws IllegalArgumentException if i <= x
*/
public void method(int i) {
if (i <= x) {
throw new IllegalArgumentException("i must be > x");
}
this.value += i;
}
Upvotes: 7
Reputation: 280030
That are no built-in preconditions for method (or constructor) arguments. Either check them at the calling site or within the method (or constructor). You have two options: throw an exception within the method or don't call the method.
Upvotes: 2
Reputation: 178263
There is no syntax in Java that can restrict the range of a parameter. If it takes an int
, then all possible values of int
are legal to pass.
You can however test the value with code in the method and throw an IllegalArgumentException
if i
is not greater than x
.
Upvotes: 9