It seems to be possible in Java to write something like this:
private enum TrafficLight { RED, GREEN; public String toString() { return //what should I return here if I want to return //"abc" when red and "def" when green? } }
Now, I'd like to know if it possible to returnin the toString method "abc" when the enum's value is red and "def" when it's green. Also, is it possible to do like in C#, where you can do this?:
private enum TrafficLight { RED = 0, GREEN = 15 ... }
I've tried this but it but I'm getting compiler errors with it.
Thanks
The Java Enum has two methods that retrieve that value of an enum constant, name() and . toString(). The toString() method calls the name() method which returns the string representation of the enum constant.
ToString(String)Converts the value of this instance to its equivalent string representation using the specified format.
The toString() method of Enum class returns the name of this enum constant, as the declaration contains. The toString() method can be overridden, although it's not essential.
You can do it as follows:
private enum TrafficLight { // using the constructor defined below RED("abc"), GREEN("def"); // Member to hold the name private String string; // constructor to set the string TrafficLight(String name){string = name;} // the toString just returns the given name @Override public String toString() { return string; } }
You can add as many methods and members as you like. I believe you can even add multiple constructors. All constructors must be private
.
An enum
in Java is basically a class
that has a set number of instances.
enum TrafficLight { RED, GREEN; @Override public String toString() { switch(this) { case RED: return "abc"; case GREEN: return "def"; default: throw new IllegalArgumentException(); } } }
enum TrafficLight { RED(0), GREEN(15); int value; TrafficLight(int value) { this.value = value; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With