Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do Enum instances get created?

Tags:

java

enums

I have a simple question regarding Enums in Java Please refer to the following code . When do the instances like PropName .CONTENTS get instantiated ?

public enum PropName {

  CONTENTS("contents"),
  USE_QUOTES("useQuotes"),
  ONKEYDOWN("onkeydown"),
  BROWSER_ENTIRE_TABLE("browseEntireTable"),
  COLUMN_HEADINGS("columnHeadings"),
  PAGE_SIZE("pageSize"),
  POPUP_TITLE("popupTitle"),
  FILTER_COL("filterCol"),
  SQL_SELECT("sqlSelect"),
  ;

  private String name;

  private PropName(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }
}
like image 448
Geek Avatar asked Sep 28 '12 11:09

Geek


People also ask

Can you create an instance of an enum?

10) You can not create an instance of enums by using a new operator in Java because the constructor of Enum in Java can only be private and Enums constants can only be created inside Enums itself. 11) An instance of Enum in Java is created when any Enum constants are first called or referenced in code.

When should an enum be used?

You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.

Why do we create enums?

Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes, command-line flags, etc. It is not necessary that the set of constants in an enum type stay fixed for all time. A Java enumeration is a class type.

How do I find the enum instance?

Enum valueOf() The valueOf() method can be used to obtain an instance of the enum class for a given String value. Here is an example: Level level = Level.


2 Answers

It's created when the class is loaded, just like any static code block.

like image 124
Denys Séguret Avatar answered Oct 21 '22 22:10

Denys Séguret


When the PropName class is loaded by the class loader. Enum constants are static final fields of their class.

like image 5
JB Nizet Avatar answered Oct 21 '22 20:10

JB Nizet