Are Java enums considered primitive or reference types?

前端 未结 4 1837
臣服心动
臣服心动 2021-02-01 12:28

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

4条回答
  •  忘掉有多难
    2021-02-01 12:47

    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.

提交回复
热议问题