iTEgg
iTEgg

Reputation: 8342

Java Enum without encapsulating it in a class

I have a situation where I need the Checker enum below used in multiple classes:

package Sartre.Connect4;

public enum Checker {
    EMPTY,
    RED,
    YELLOW
}

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

example:

    public Cell(){

    currentCell = Checker.EMPTY;

}

example:

    public Cell(Checker checker){

    currentCell = checker;
}

and the code compiles fine and runs fine also.

so what is my question? well being new to Java I am just wondering if the way I use Checker without encapsulating it in a class is a sound implementation?

it may be because of The enum declaration defines a class (called an enum type). as noted in Java docs enum tutorial page.

Upvotes: 4

Views: 1128

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137567

That all looks perfectly sound to me. Java's enum values are objects of the class with the name of the overall enumeration; as it is a class, treat it just like any other class. You can even attach more methods to them, though that's not really my favored approach.

The other useful trick when you are using a particular value of the enumeration a lot in some other source file is to import static that value. That allows you to use it without having to qualify it (assuming it's not ambiguous of course). Some people frown on the technique, but I like it since it keeps the uses cleaner and your IDE can always tell you exactly what's going on. (I don't recommend writing Java without an IDE to support you.)

Upvotes: 2

Bozho
Bozho

Reputation: 597076

Yes, this is perfectly fine.

Although, if the Checker is 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 construct the Cell by calling:

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

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

Upvotes: 2

Related Questions