Java Enum without encapsulation in a class

I have a situation where I need the Checker enumeration below, used in several classes:

package Sartre.Connect4; public enum Checker { EMPTY, RED, YELLOW } 

so I put Checker in the Checker.java file, and then from the classes that need it, I just do the following:

Example:

  public Cell(){ currentCell = Checker.EMPTY; } 

Example:

  public Cell(Checker checker){ currentCell = checker; } 

and the code compiles fine and works great.

So what is my question? good to be new to Java I just wonder if the way I use Checker without encapsulating it in a class is a reliable implementation?

this may be because an enum declaration defines a class (called an enum type) , as described in the article on renaming Java documents.

+4
source share
2 answers

It all looks great to me. Java enum values ​​are class objects with a common enumeration name; since this is a class, treat it like you would any other class. You can even apply more methods to them, although this is not my favorite approach.

Another useful trick, when you often use a certain number of enumerations in some other source file, is import static this value. This allows you to use it without the need for its qualifications (provided that it is not ambiguous, of course). Some people frowned on the technology, but I like it because it helps to use a cleaner, and your IDE can always tell you exactly what is going on. (I do not recommend writing Java without IDE support to support you.)

+2
source

Yes, that's great.

Although, if Checker used only by this class, you can define it as a static inner class:

 public class Cell { public Cell(Checker checker) {..} // remainder omitted public static enum Checker { EMPTY, RED, YELLOW }; } 

And build Cell by calling:

 Cell cell = new Cell(Cell.Checker.RED); 

If it is used by other classes, then the only solution is to have it as a separate public class.

+2
source

Source: https://habr.com/ru/post/1310901/


All Articles