1

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

Programmer
  • 23
  • 4
  • Does this answer your question? [How to get an enum value from a string value in Java](https://stackoverflow.com/questions/604424/how-to-get-an-enum-value-from-a-string-value-in-java) – Hanchen Jiang Jan 22 '22 at 16:25
  • @HanchenJiang enum is the best solution, but not the only solution. – hfontanez Jan 22 '22 at 16:40
  • In Java, a class or enum name (type) cannot start with a number. – hfontanez Jan 22 '22 at 16:43
  • Did I answer your question? – hfontanez Jan 22 '22 at 16:58
  • Samer, I know English is not your primary language, but I am sorry to say that your post doesn't make any sense. Because of that, your question is being voted for closing due to lack of clarity. Write your problem in your language and run it thru Google translate or similar service. Then come here and post the English translation. We won't be able to help you unless we understand what you are trying to accomplish. – hfontanez Jan 22 '22 at 22:00

1 Answers1

2

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".

hfontanez
  • 5,774
  • 2
  • 25
  • 37