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.
That all looks perfectly sound to me. Java’s
enumvalues 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 staticthat 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.)