I have a class with a list of enums, The enums are passed to a constructor and updated to the toString, but I am not allowed to have an instance variable on the class (part of the requirement). How can I make the enums output like the String without adding an instance?
public enum Other {
GAME_BOY("Game Boy"), MACBOOK("Macbook Pro"), IPHONE("iPhone XS"), LAPTOP("Laptop");
private final String product; //can't have instance variable
private Other(String passed) {
this.product = passed;
}
@Override
public String toString() {
return product;
}
}
You can override toString() for each element:
public enum Other {
GAME_BOY {
@Override public String toString() { return "Game Boy"; }
},
MACBOOK { ... },
...
}
See this code run live at IdeOne.com.
Alternatively, you can put a switch statement in the toString method:
@Override
public String toString() {
switch (this) {
case GAME_BOY:
return "Game boy";
case MACBOOK:
return "Macbook Pro";
...
}
}
How about the following:-
public enum Other {
GAME_BOY, MACBOOK, IPHONE, LAPTOP;
@Override
public String toString() {
switch(this) {
case GAME_BOY:
return "Game Boy";
case MACBOOK:
return "Macbook Pro";
case IPHONE:
return "iPhone XS";
case LAPTOP:
return "Laptop";
default:
return null;
}
}
public static void main(String[] args) {
System.out.println("The value of the other is " + Other.GAME_BOY.toString());
}
}