Creating a method that can only input a certain types of strings that are predetermined
I have the following type of Strings
"Move 1 place forwards";
"Move 1 place backwards;
Can I create a type called 2dMotion, where a method can only take in these two strings as arguments in Java.
public 2dMotion message(){ return "Move 1 place forwards"; }
For example if a method was classed that had 2dMotion as an input then it wouldn't be able to input anything but those 2 sentences
You can declare them as constants in a class, and provide direct access to them by making them public:
public MyClass {
public static final MOTION_FORWARD = "Move 1 place forward";
public static final MOTION_BACKWARDS = "Move 1 place backwards";
// Rest of the class omitted
}
Or, a better solution is to use an Enum.
public enum MOTION {
FORWARD("Move 1 place forward"),BACKWARDS("Move 1 place backwards");
private final String val;
private MOTION(String val) {
this.val = val;
}
public String getVal() {
return val;
}
}
To use the constant, simply use MyClass.MOTION_FORWARD
. To use the enum, you could do MOTION.FORWARD.getVal();
Lastly, as good practice, you should override toString()
method:
@Override
public String toString() {
return val;
}
Even though this method does the same as getVal()
, it is consider good practice to do so. If you would like to remove one of those methods, it should be the getVal()
method. Also, even though the enum solution involves more code, it is also considered to be a better solution. Also, when you override toString()
, it allows to return the value of the enum without invoking toString()
or getVal()
directly. For example, System.out.println(MOTION.BACKWARDS);
prints out "Move 1 place backwards".