Reputation: 36
I have a class that has some constants, I have a method and I do like to restrict it's parameters to those constants defined in the class, is there a way to make this happen in java?
Upvotes: 0
Views: 69
Reputation: 6969
Constants:
enum DistanceUnit {
MILE,
KILOMETER
}
double calculateCaloriesBurned (double distanceWalked, DistanceUnit unit);
Along the same lines, suppose you didn't like people walking negative distances:
class Distance {
private double value;
public Distance (value) {
if (value < 0) { throw new IllegalArgumentException(); }
...
}
}
double calculateCaloriesBurned (Distance distanceWalked, DistanceUnit unit);
Upvotes: 2
Reputation: 285405
Use enums for this. They are constants that allow for compile-time type checking, and in fact this is one of the very reasons that they were created.
Upvotes: 6