Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Enum instances are created magically by the C-like syntax <code>public enum E { A, B, C }</code> and you cannot add more instances, even if they would be known at compile time.</p> <p>Depending on how much logic you have to attach to each enum instance and how many different "sub-enum" categories you have, you can try one of these approaches:</p> <h3>Single enum class with parameters</h3> <pre class="lang-java prettyprint-override"><code>public enum Day { MONDAY(false), TUESDAY(false), WEDNESDAY(false), THURSDAY(false), FRIDAY(false), SATURDAY(true), SUNDAY(true); private final boolean weekend; private Day(boolean weekend) { this.weekend = weekend; } public boolean isWeekend() { return weekend; } public void doSomething() { if (isWeekend()) { // have fun } else { // do some work } } } </code></pre> <p>Pros: this approach allows you to have a single enum class (so for example you can iterate easily on all instances), is simple, and adds no boilerplate.</p> <p>Cons: if you test often for category membership your code will become cluttered with <code>if</code>s; you cannot enforce at compile time that a variable refers to an instance of a specific category.</p> <h3>Enums implementing interfaces</h3> <pre class="lang-java prettyprint-override"><code>public interface Day { public void doSomething(); } public enum WorkDay implements Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY; @Override public void doSomething() { // do some work } } public enum WeekEnd implements Day { SATURDAY, SUNDAY; @Override public void doSomething() { // have fun } } </code></pre> <p>Pros: you can have type safe references to instances of a single category; you can isolate category specific code in methods, reducing the need for membership tests; can be extended without modifying the original code.</p> <p>Cons: requires some boilerplate (maybe too much for simple cases); you do not get an automatically generated collection of all instances.</p> <p>See this answer for more examples of <a href="https://stackoverflow.com/a/15147361/2093341">enums implementing interfaces</a>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload