I have a enum which looks like:
public enum Constants{
YES(\"y\"), NO(\"N\")
private String value;
Constants(String value){
this.value = value;
Create a getValue() method in your enum, and use this instead of toString().
public enum Constants{
YES("y"), NO("N")
private String value;
Constants(String value){
this.value = value;
}
}
public String getValue(){
return value;
}
And instead of:
System.out.println(Constants.YES.toString())
System.out.println(Constants.NO.toString())
(Which are also missing a semi-colon), use
System.out.println(Constants.YES.getValue());
System.out.println(Constants.NO.getValue());
Hope this solved your problem. If you do not want to create a method in your enum, you can make your value field public, but this would break encapsulation.
You can also add a getter to the enumeration and simply call on it to access the instance variable:
public enum Constants{
YES("Y"), NO("N");
private String value;
public String getResponse() {
return value;
}
Constants(String value){
this.value = value;
}
}
public class TestConstants{
public static void main(String[] args){
System.out.println(Constants.YES.getResponse());
System.out.println(Constants.NO.getResponse());
}
}
Write Getter and Setter for value
and use:
System.out.println(Constants.YES.getValue());
System.out.println(Constants.NO.getValue());
String enumValue = Constants.valueOf("YES")
Java doc ref: https://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html#valueOf(java.lang.Class,%20java.lang.String)
You need to override the toString
method of your enum:
public enum Constants{
YES("y"), NO("N")
// No changes
@Override
public String toString() {
return value;
}
}