tags:

views:

77

answers:

2

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.

thank you for your insight into this matter.

+2  A: 

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.

Bozho
no, it is used by 2 other classes.
iEisenhower
yes the way you mentioned was the way i developed it initially but then the design changed so i need it to be avaliable in other classes also. thank you for clearing up the new implementation as valid.
iEisenhower
+2  A: 

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.)

Donal Fellows
ok i understand now. import it the way packages are imported. :)
iEisenhower