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.

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu