If I开发者_如何学JAVA have an enum object, is it considered a primitive or a reference?
It's a reference type. Java primitives are boolean byte short char int long float double
.
You can get the enumeration constant's value by calling ordinal()
, which is used by EnumSet and EnumMap iterator
and "traverses the elements in their natural order (the order in which the enum constants are declared)"
You can even add your own members to the enum class, like this:
public enum Operation {
PLUS { double eval(double x, double y) { return x + y; } },
MINUS { double eval(double x, double y) { return x - y; } },
TIMES { double eval(double x, double y) { return x * y; } },
DIVIDE { double eval(double x, double y) { return x / y; } };
// Do arithmetic op represented by this constant
abstract double eval(double x, double y);
}
//Elsewhere:
Operation op = Operation.PLUS;
double two = op.eval(1, 1);
The way enums work is actually not too different from how they were used before their introduction with Java 5:
public final class Suit {
public static final Suit CLUBS = new Suit();
public static final Suit DIAMONDS = new Suit();
public static final Suit HEARTS = new Suit();
public static final Suit SPADES = new Suit();
/**
* Prevent external instantiation.
*/
private Suit() {
// No implementation
}}
By instantiating the different suits on class loading it is ensured that these will be mutually exclusive and the private constructor ensures that no further instances will be created.
These would be comparable either through == or equals.
The Java 5 enum works pretty much the same way, but with some necessary features to support serialization etc.
I hope this background sheds some further light.
This article essentially shows you how enums are implemented, and as SLaks says, they are references.
Enums are reference types, in that they can have methods and can be executed from command line as well , if they have main method.
See following "Planet" example from Sun/Oracle
http://download.oracle.com/javase/tutorial/java/javaOO/enum.html
精彩评论