Reputation:
I want to have a string assigned to each enum so that when the toString()
method is called on an enum it will return the string. I have tried the code below based on what I was able to find on my own but get an error:
RecycleCode(String) is undefined.
How do I assign a string to an enum and then return it using the toString()
method?
public enum RecycleCode {
ONE("PET"),
TWO("HDPE"),
THREE("PVC"),
FOUR("LDPE"),
FIVE("PP"),
SIX("PS"),
SEVEN("OTHER"),
ABS("ABS");
public String toString() {
return name();
}
}
Upvotes: 0
Views: 46
Reputation: 178263
You are passing a String
in each of your enum declarations, but you don't have a constructor that accepts a String
, or an instance variable to hold it. Try
private String name;
private RecycleCode(String name) {
this.name = name;
}
Then you can reference the instance variable name
in your toString()
method.
return name;
Upvotes: 4
Reputation: 2607
public enum RecycleCode {
ONE("PET"),
TWO("HDPE"),
THREE("PVC"),
FOUR("LDPE"),
FIVE("PP"),
SIX("PS"),
SEVEN("OTHER"),
ABS("ABS");
private String name;
public RecycleCode(String name) {
this.name = name;
}
public String toString(){
return name;
}
}
Upvotes: 2