Segmond
Segmond

Reputation: 36

Is it possible to limit parameters passed to a method to constants?

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

Answers (2)

iluxa
iluxa

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

Hovercraft Full Of Eels
Hovercraft Full Of Eels

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

Related Questions