Java | How to access Enum’s public method?
Enum is an enumerated types, a special type in Java that used to hold static information.
Eg: the state of a connection (CONNECTING, CONNECTED, DISCONNECTED, etc), the day (MONDAY, TUESDAY, etc).
Besides of defining a status, we also can include some useful features of the Enum and write it as a method in the Enum.
Here is a simple example I write to show how to access to Enum’s method.
I have a Enum here, named “Day”:
package alfred.playground; public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; public boolean isWeekday() { return (equals(MONDAY) || equals(TUESDAY) || equals(WEDNESDAY) || equals(THURSDAY) || equals(FRIDAY)); } public boolean isWeekend() { return (equals(SATURDAY) || equals(SUNDAY)); } }
And, here is the test program:
Day day1 = Day.THURSDAY; System.out.println(String.format("[%s] is weekend? [%b]", day1, day1.isWeekend())); /*$> [THURSDAY] is weekend? [false] */ Day day2 = Day.SATURDAY; System.out.println(String.format("[%s] is weekend? [%b]", day2, day2.isWeekend())); /*$> [SATURDAY] is weekend? [true] */
In order to call Enum’s method, we can not just directly call as usual class’s method “myClass.doSomething()”.
Instead, we must assign a value to the Enum before we can invoke the method.
For shorter codes, we can simplified the code by skipping the value assignment line:
System.out.println(String.format("[%s] is weekend? [%b]", Day.FRIDAY, Day.FRIDAY.isWeekday())); /*$> [FRIDAY] is weekday? [true] */
Leave a Reply