Are explicit enumerations considered primitive or reference types?

If I have an enumeration object, is it considered primitive or reference?

+44
java
Jul 12 '10 at 19:41
source share
4 answers

This is a reference type.

Unlike many languages ​​in which enum is a set of integral constants, Java enumerations are immutable instances of objects. You can get the numeric value of an enum instance by calling ordinal() .

You can even add your own members to the enum class, for example:

 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); 
+50
Jul 12 2018-10-12T00:
source share

Working with enumerations is actually not too different from how they were used before they were introduced 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 creating instances of various stripes when loading classes, it is ensured that they are mutually exclusive, and the private constructor ensures that no additional instances are created.

They would be comparable either through == or equal.

Java 5 interception works in much the same way, but with some necessary features to support serialization, etc.

I hope this background sheds some extra light.

+10
Jul 13 '10 at 0:44
source share

This article essentially shows how enums are implemented, and, as SLaks says, these are links.

0
Jul 12 '10 at 19:46
source share

Enumerations are reference types because they can have methods and can be executed from the command line if they have a main method.

See the Planet Example from Sun / Oracle

http://download.oracle.com/javase/tutorial/java/javaOO/enum.html

0
Jan 25 '11 at 16:10
source share



All Articles