Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum as instance variables

Tags:

java

enums

scjp

If you have an enum such as

enum Coffee {
    BIG,
    SMALL
}

and a class that has an instance variable like this of the enum:

public class MyClass {
    private Coffee coffee;

    // Constructor etc.
}

Why is it possible in the constructor to say e.g. coffee.BIG? I don't understand that you can use the reference? Is enum as instance variables initialized to something other than null? It is the self test question #4 in the SCJP book in the first chapter. I tried to shorten the code and question.

like image 928
LuckyLuke Avatar asked Aug 04 '12 12:08

LuckyLuke


1 Answers

In

enum Coffee {
    BIG,
    SMALL
}

BIG or SMALL are public static final fields of Coffee class, and like all static fields they can be accessed by class name like

Coffee b1 = Coffee.BIG;

or by reference of same type as class, like

Coffee s2 = b1.SMALL;
Coffee s3 = Coffee.BIG.SMALL; //BIG is reference of type Coffee so it is OK (but looks strange)

But lets remember that we should avoid accessing static members via references. This creates confusion since we are not really accessing members of instance but members of class (so for instance there is no polymorphic behaviour).

like image 188
Pshemo Avatar answered Sep 19 '22 20:09

Pshemo