0

我有一个有一些常量的类,我有一个方法,我喜欢将它的参数限制为类中定义的那些常量,有没有办法在 java 中实现这一点?

4

2 回答 2

6

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.

于 2013-10-18T02:15:14.207 回答
2

常数:

enum DistanceUnit {
  MILE,
  KILOMETER
}

double calculateCaloriesBurned (double distanceWalked, DistanceUnit unit);

同样,假设您不喜欢人们走负距离:

class Distance {
  private double value;

  public Distance (value) {
    if (value < 0) { throw new IllegalArgumentException(); }
    ...
  }
}

double calculateCaloriesBurned (Distance distanceWalked, DistanceUnit unit);
于 2013-10-18T02:22:17.837 回答