Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate enum class

Tags:

java

enums

Consider I am having the following enum class,

public enum Sample {
    READ,
    WRITE
}

and in the following class I am trying to test the enum class,

public class SampleTest {
    public static void main(String[] args) {
        testEnumSample(Sample.READ);
    }

    public static void testEnumSample(Sample sample) {
        System.out.println(sample);
    }
}

Here I am specifying Sample.READ then passing it as the parameter to the method testEnumSample. Instead if we want to instantiate the enum class and pass it as parameter what we need to do?

like image 365
Hariharan Avatar asked May 31 '13 06:05

Hariharan


People also ask

Can you instantiate an enum class?

You do not instantiate an enum , but rely the constants defined. Enums can be used in a switch-case statement, just like an int .

Can we create object for enum class in Java?

An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

Can we initialize enum in Java?

The enum constants have an initial value which starts from 0, 1, 2, 3, and so on. But, we can initialize the specific value to the enum constants by defining fields and constructors. As specified earlier, Enum can have fields, constructors, and methods.

How do you declare an enum?

An enum is defined using the enum keyword, directly inside a namespace, class, or structure. All the constant names can be declared inside the curly brackets and separated by a comma. The following defines an enum for the weekdays. Above, the WeekDays enum declares members in each line separated by a comma.


1 Answers

Here I need to specifying Sample.READ to pass it as parameter. Instead if we want to instantiate the enum class and pass it as parameter what we need to do?

What would "instantiate the enum class" even mean? The point of an enum is that there are a fixed set of values - you can't create more later. If you want to do so, you shouldn't be using an enum.

There are other ways of getting enum values though. For example, you could get the first-declared value:

testEnumSample(Sample.values()[0]);

or perhaps pass in the name and use Sample.valueOf:

testEnumSample("READ");

...

Sample sample = Sample.valueOf(sampleName);

If you explained what you were trying to achieve, it would make it easier to help you.

like image 137
Jon Skeet Avatar answered Oct 07 '22 19:10

Jon Skeet