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?
You do not instantiate an enum , but rely the constants defined. Enums can be used in a switch-case statement, just like an int .
An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With