Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Java enum constructor

In Java, an enumeration is a special kind of class that represents a fixed number of predefined values. The values are defined as Enum constants, which are static and final fields of the enumeration.

When you define an enum, you can also define a Constructor for it, which is called when each enum constant is created. The constructor is passed the values of the constant's fields and can use those values to initialize the constant.

Here's an example of an enumeration called Size with a constructor that takes a single String argument:


In this example, the Size enumeration has four constants: SMALL, MEDIUM, LARGE, and EXTRA_LARGE. Each constant has an associated abbreviation, which is passed to the constructor when the constant is created. The constructor sets the value of the abbreviation field to the passed-in value.

You can call the constructor explicitly or it will be called automatically when enum constants are created, so the following code:

Size s = Size.SMALL;

is equivalent to

Size s = new Size("S");

When you define constructors for your enum, it is a best practice to make them private. So that no other classes can create an instance of your Enum. This way you can only use the predefined values of the Enum and not create any new value on runtime.



This post first appeared on Java Tutorial - InstanceOfJava, please read the originial post: here

Share the post

Java enum constructor

×

Subscribe to Java Tutorial - Instanceofjava

Get updates delivered right to your inbox!

Thank you for your subscription

×