Alan2
Alan2

Reputation: 24562

Alternative way to create a java enum?

I have the following code that I am trying to understand:

public class A {    
    enum Size {S, M, L };  
    Size size = Size.M; 
} 

I understand the first enum line is creating an enum with three values but what is the second line doing? What will the variable size hold and is this another way to construct an enum?

Upvotes: 0

Views: 180

Answers (3)

Denys Séguret
Denys Séguret

Reputation: 382102

The second line is just giving to the field size (of type Size) of the instance of class A the initial value Size.M.

You may be a little disturbed here by the fact that the enum is created inside the class A, it could have been in another file (but it's perfectly OK to put it inside the class A if it's used only there).


EDIT (not really part of the answer) : here's a (not pretty) exemple of enum declaration so that you can better understand the form of an enum declaration :

public enum QueryError {

    no_request("no_request", "No request in client call"),
    no_alias_requested("no_alias_requested", "no alias requested"),
    session_not_found("session_not_found", "wrong session id"),
    synosteelQuery_not_found("sxxx_not_found", "sxxx not found");

    public JsonpServerResponse.Error error;

    private QueryError(String type, String details) {
        this.error = new JsonpServerResponse.Error();
        this.error.type = type;
        this.error.detail = details;
    }
}

Upvotes: 6

Jacob Mattison
Jacob Mattison

Reputation: 51052

An enum is a type (just as a class is a type). The second line is creating an instance variable called size, which has a type of Size (since an enum is a type). Then it's initializing the value of that instance variable to an instance of the enum Size (specifically, the Size.M instance).

Upvotes: 0

duffymo
duffymo

Reputation: 308743

The second like is declaring a package private member variable of type Size in your class A and initializing it to point to Size.M.

Upvotes: 0

Related Questions