i tried to use an enum for my first time. For some Tests i want to override the toString method of my enum and return a String with the chosen enum.
Heres my code so far:
@Override
public String toString()
{
return "Fahrzeuge{" +
switch(this)
{
case MOTORAD: "1"; break;
case LKW: "2"; break;
case PKW: "3"; break;
case FAHRRAD: "4"; break;
}
+
"typ:" + this.typ +
", ps:" + this.ps +
", reifen:" + this.reifen +
", gewicht:" + this.gewicht +
"}";
}
IntelliJ underline my cases and tell me the following: "Not a Statement" => I guess this makes sense, if it's not allowed to build a String with a switch - case.
So far so good, but it seem's to be impossible to return a String which is build through a switch case, or did i make a mistake at my return? Any other options to return the chosen enum? I could add an attribute that hold my chosen enums name, but i though i could do this a bit simpler.
Thanks for help
I think you really don't need the switch Statement because the superclass of the enum already knows the name of your "type":
@Override
public String toString()
{
return "Fahrzeuge: " + super.toString() +
", ps:" + this.ps +
", reifen:" + this.reifen +
", gewicht:" + this.gewicht;
}
Simply call the toString() method of the super class and you get the string value of your currently selected enum-type. You even can delete your type string.