0
Having Methods Take Constant Parameters (Java)
Programmers, I have another question about an exercise in "The Java Programming Language, Fourth Edition" by Ken Arnold, James Gosling, and David Holmes. Exercise 2.17 reads as follows: "Add two turn methods to [class] Vehicle: one that takes a number of degrees to turn and one that takes either of the constants Vehicle.TURN_LEFT or Vehicle.TURN_RIGHT." Is there a way to force a method to only take particular constant parameters? Simply changing the relevant method signatures like so: public void turn(int degrees) public void turn(final int degrees) isn't enough to prevent compile-time errors. I'd appreciate anyone's input on this question. Thank you. Peter
2 Respuestas
+ 4
If you want to accept only fixed values, then you should create an enum for that:
enum TURN {
LEFT(-30),
RIGHT (30);
private int degree;
private TURN(int degree) {
this.degree = degree;
}
public int getDegree() {
return degree;
}
}
public void turn(TURN t) {
turn(t.getDegree());
}
0
This was helpful. Thank you!