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);
Internally, enums will be translated to something like this
class Sample extends Enum {
public static final Sample READ = new Sample("READ", 0);
public static final Sample WRITE = new Sample("WRITE", 1);
private Sample(String s, int i) {
super(s, i);
}
// More methods, e.g. getter
}
Use Enum.valueOf()
static function, then cast it into your enum type.
Enum v = Enum.valueOf(TheEnumClass, valueInString);
Use class.getEnumConstants()
function to get the list of the enum constants, and loop this list and get.
Plugins[] plugins = Plugins.class.getEnumConstants();
for (Plugins plugin: plugins) {
// use plugin.name() to get name and compare
}
You cannot create a new enum instance. Otherwise it won't be an enum. You can reference an already existing enum. As in your example
Sample sample = Sample.READ;
I'm answering to the first question. You can easily do it like this:
public static void main(String[] args) {
Sample.READ.testEnumSample();
}
public enum Sample {
READ,
WRITE;
public void testEnumSample() {
System.out.println(this);
}
}
You cannot instantiate an Enum, thats the whole point of having an Enum. For example you would use enum when defining properties of some thing which would never change like:
enum TrafficLight {
RED("stop"),
YELLOW("look"),
GREEN("go")
}
private string value;
private TrafficLight(String value) {
this.value = value;
}
private TrafficLight(String value) {
this.value = value;
}
public getValue() {
return value;
}
In the following example, Planet is an enum type that represents the planets in the solar system. They are defined with constant mass and radius properties.,An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.,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.,Each enum constant is declared with values for the mass and radius parameters. These values are passed to the constructor when the constant is created. Java requires that the constants be defined first, prior to any fields or methods. Also, when there are fields and methods, the list of enum constants must end with a semicolon.
public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
public class EnumTest {
Day day;
public EnumTest(Day day) {
this.day = day;
}
public void tellItLikeItIs() {
switch (day) {
case MONDAY:
System.out.println("Mondays are bad.");
break;
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-so.");
break;
}
}
public static void main(String[] args) {
EnumTest firstDay = new EnumTest(Day.MONDAY);
firstDay.tellItLikeItIs();
EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
thirdDay.tellItLikeItIs();
EnumTest fifthDay = new EnumTest(Day.FRIDAY);
fifthDay.tellItLikeItIs();
EnumTest sixthDay = new EnumTest(Day.SATURDAY);
sixthDay.tellItLikeItIs();
EnumTest seventhDay = new EnumTest(Day.SUNDAY);
seventhDay.tellItLikeItIs();
}
}
Mondays are bad. Midweek days are so - so. Fridays are better. Weekends are best. Weekends are best.
for (Planet p: Planet.values()) {
System.out.printf("Your weight on %s is %f%n",
p, p.surfaceWeight(mass));
}
public enum Planet {
MERCURY (3.303e+23, 2.4397e6),
VENUS (4.869e+24, 6.0518e6),
EARTH (5.976e+24, 6.37814e6),
MARS (6.421e+23, 3.3972e6),
JUPITER (1.9e+27, 7.1492e7),
SATURN (5.688e+26, 6.0268e7),
URANUS (8.686e+25, 2.5559e7),
NEPTUNE (1.024e+26, 2.4746e7);
private final double mass; // in kilograms
private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
private double mass() { return mass; }
private double radius() { return radius; }
// universal gravitational constant (m3 kg-1 s-2)
public static final double G = 6.67300E-11;
double surfaceGravity() {
return G * mass / (radius * radius);
}
double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java Planet <earth_weight>");
System.exit(-1);
}
double earthWeight = Double.parseDouble(args[0]);
double mass = earthWeight/EARTH.surfaceGravity();
for (Planet p : Planet.values())
System.out.printf("Your weight on %s is %f%n",
p, p.surfaceWeight(mass));
}
}
$ java Planet 175 Your weight on MERCURY is 66.107583 Your weight on VENUS is 158.374842 Your weight on EARTH is 175.000000 Your weight on MARS is 66.279007 Your weight on JUPITER is 442.847567 Your weight on SATURN is 186.552719 Your weight on URANUS is 158.397260 Your weight on NEPTUNE is 199.207413
In this example I have to instantiate by calling the .value() enum method. but when you instantiate a class normally, all you do is Class(value). Would it be possible to implement something similar to enum variants that holds a class? For example:, 1 day ago Mar 16, 2016 · @Sahar. I am not instantiating an enum. I am just trying to pass an enum without any values or constants in the constructor. As others have mentioned that null is a valid value and this is the default for enum as well but if I pass null i get no code coverage. – , Enumerations are iterable. They can be iterated using loops 5. Enumerations support hashing. Enums can be used in dictionaries or sets. 1. By value :- In this method, the value of enum member is passed. ,I recently found out you can use enums in Python, but I'm not happy with how my code is working and I'm wondering if there is a cleaner way to implement it.
from enum
import Enum class Hex: def __init__(self, hex_code: str): self.code = hex_code class Rgb: def __init__(self, R: int, G: int, B: int): self.r = R self.g = G self.b = B class Color(Enum): HEX = Hex RGB = Rgb def main(): hex_color = Color.HEX.value('#00FF00') rgb_color = Color.RGB.value(255, 255, 255) if __name__ == "__main__": main()
Public MustInherit Class GeneralClass '...Enum GeneralClassType A = 1 B = 2End EnumPublic Shared Function BuildClass(Val as Integer, ParamArray par() as Object) as GeneralClass Dim NewObject as GeneralClass = Nothing Select Case Ctype(Val, GeneralClassType) Case GeneralClassType.A NewObject = new ACase GeneralClassType.B NewObject = new B Case else throw new exception("invalid type.") end select NewObject.setPar(par) return NewObjectend function End Class Public Class AInherits GeneralClass'...End Class Public Class BInherits GeneralClass '... End Class
public
function InstantiateClass(of T)() as TDim NewObject as GeneralClass = GetType(T).GetConstructor(New Type() {}).Invoke(New Object() {}) return NewObject end class
Dim Var1 as GeneralClass = InstantiateClass(of A)()
Public Class Form1Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click Dim BaseFlag As Integer = 2 Dim BaseName As String = "Create a class from enum"
Dim T As BaseTest = BaseTest.Build(BaseFlag, BaseName) MsgBox(T.GetClassTypeName) End Sub End Class Public MustInherit Class BaseTestProtected Name As StringEnum TestType TestA = 1 TestB = 2 TestC = 3 End EnumPublic Function GetClassTypeName() As String Return String.Concat(Name, ". The final class is: ", Me.GetType.FullName, "") End FunctionPublic Shared Function Build(BaseFlag As Integer, Name As String) As BaseTest Dim NS As String = GetType(BaseTest).FullName Dim Index As Integer = NS.LastIndexOf(".") + 1 NS = NS.Substring(0, Index) Dim ClassType As String = CType(BaseFlag, TestType).ToString() Dim Test As BaseTest = Activator.CreateInstance(Type.GetType(NS & ClassType)) Test.Name = Name Return TestEnd Function End Class Public Class TestBInherits BaseTest End Class
Dim o As Object = Activator.CreateInstance(Type.GetType("MyNameSpace.A"))
Last modified: July 4, 2022
Here's a quick and simple example of an enum that defines the status of a pizza order; the order status can be ORDERED, READY or DELIVERED:
public enum PizzaStatus { ORDERED, READY, DELIVERED; }
Now that we have a basic understanding of what enums are and how we can use them, we'll take our previous example to the next level by defining some extra API methods on the enum:
public class Pizza {
private PizzaStatus status;
public enum PizzaStatus {
ORDERED,
READY,
DELIVERED;
}
public boolean isDeliverable() {
if (getStatus() == PizzaStatus.READY) {
return true;
}
return false;
}
// Methods that set and get the status variable.
}
First, we'll look at run-time safety in the following snippet, where we'll use the “==” operator to compare statuses. Either value can be null and we won't get a NullPointerException. Conversely, if we use the equals method, we will get a NullPointerException:
if (testPz.getStatus().equals(Pizza.PizzaStatus.DELIVERED)); if (testPz.getStatus() == Pizza.PizzaStatus.DELIVERED);
We can use enum types in switch statements also:
public int getDeliveryTimeInDays() {
switch (status) {
case ORDERED:
return 5;
case READY:
return 2;
case DELIVERED:
return 0;
}
return 0;
}
Next, let's extend the example above by implementing the transition from one stage of a pizza order to another. We'll see how we can get rid of the if and switch statements used before:
public class Pizza {
private PizzaStatus status;
public enum PizzaStatus {
ORDERED(5) {
@Override
public boolean isOrdered() {
return true;
}
},
READY(2) {
@Override
public boolean isReady() {
return true;
}
},
DELIVERED(0) {
@Override
public boolean isDelivered() {
return true;
}
};
private int timeToDelivery;
public boolean isOrdered() {
return false;
}
public boolean isReady() {
return false;
}
public boolean isDelivered() {
return false;
}
public int getTimeToDelivery() {
return timeToDelivery;
}
PizzaStatus(int timeToDelivery) {
this.timeToDelivery = timeToDelivery;
}
}
public boolean isDeliverable() {
return this.status.isReady();
}
public void printTimeToDeliver() {
System.out.println("Time to delivery is " +
this.getStatus().getTimeToDelivery());
}
// Methods that set and get the status variable.
}
The most interesting thing about Enum members is that they are singletons. EnumMeta creates them all while it is creating the Enum class itself, and then puts a custom __new__() in place to ensure that no new ones are ever instantiated by returning only the existing member instances.,The reason for defaulting to 1 as the starting number and not 0 is that 0 is False in a boolean sense, but enum members all evaluate to True.,Base class for creating enumerated constants that can be combined using the bitwise operations without losing their Flag membership.,Base class for creating enumerated constants that can be combined using the bitwise operators without losing their IntFlag membership. IntFlag members are also subclasses of int.
>>> from enum
import Enum
>>>
class Color(Enum):
...RED = 1
...GREEN = 2
...BLUE = 3
...
>>> print(Color.RED)
Color.RED
>>> print(repr(Color.RED))
<Color.RED: 1>
>>> type(Color.RED)
<enum 'Color'>
>>> isinstance(Color.GREEN, Color)
True
>>>
>>> print(Color.RED.name)
RED
>>> class Shake(Enum):
...VANILLA = 7
...CHOCOLATE = 4
...COOKIES = 9
...MINT = 3
...
>>>
for shake in Shake:
...print(shake)
...
Shake.VANILLA
Shake.CHOCOLATE
Shake.COOKIES
Shake.MINT
In Java, enum types are considered to be a special type of class. It was introduced with the release of Java 5.,An enum class can include methods and fields just like regular classes.,In Java, an enum (short for enumeration) is a type that has a fixed set of constant values. We use the enum keyword to declare enums. For example,,In Java, enum was introduced to replace the use of int constants.
In Java, an enum (short for enumeration) is a type that has a fixed set of constant values. We use the enum
keyword to declare enums. For example,
enum Size { SMALL, MEDIUM, LARGE, EXTRALARGE }
Example 1: Java Enum
enum Size {
SMALL,
MEDIUM,
LARGE,
EXTRALARGE
}
class Main {
public static void main(String[] args) {
System.out.println(Size.SMALL);
System.out.println(Size.MEDIUM);
}
}
Output
SMALL MEDIUM
Here, pizzaSize is a variable of the Size type. It can only be assigned with 4 values.
pizzaSize = Size.SMALL; pizzaSize = Size.MEDIUM; pizzaSize = Size.LARGE; pizzaSize = Size.EXTRALARGE;
Example 2: Java Enum with the switch statement
enum Size {
SMALL,
MEDIUM,
LARGE,
EXTRALARGE
}
class Test {
Size pizzaSize;
public Test(Size pizzaSize) {
this.pizzaSize = pizzaSize;
}
public void orderPizza() {
switch (pizzaSize) {
case SMALL:
System.out.println("I ordered a small size pizza.");
break;
case MEDIUM:
System.out.println("I ordered a medium size pizza.");
break;
default:
System.out.println("I don't know which one to order.");
break;
}
}
}
class Main {
public static void main(String[] args) {
Test t1 = new Test(Size.MEDIUM);
t1.orderPizza();
}
}
You cannot define new methods when you are creating an enumeration. However, an enumeration type inherits a complete set of static and instance methods from the Enum class. The following sections survey most of these methods, in addition to several other methods that are commonly used when working with enumeration values.,Because enumeration types are defined by language structures, such as enum (C#), and Enum (Visual Basic), you cannot define custom methods for an enumeration type other than those methods inherited from the Enum class. However, you can use extension methods to add functionality to a particular enumeration type.,When you define a method or property that takes an enumerated constant as a value, consider validating the value. The reason is that you can cast a numeric value to the enumeration type even if that numeric value is not defined in the enumeration.,When you define a method or property that takes an enumerated constant as a value, consider validating the value. The reason is that you can cast a numeric value to the enumeration type even if that numeric value is not defined in the enumeration.
By using a particular programming language's features to cast (as in C#) or convert (as in Visual Basic) an integer value to an enumeration value. The following example creates an ArrivalStatus
object whose value is ArrivalStatus.Early
in this way.
ArrivalStatus status2 = (ArrivalStatus) 1;
Console.WriteLine("Arrival Status: {0} ({0:D})", status2);
// The example displays the following output:
// Arrival Status: Early (1)
ArrivalStatus status2 = (ArrivalStatus) 1;
Console.WriteLine("Arrival Status: {0} ({0:D})", status2);
// The example displays the following output:
// Arrival Status: Early (1)
let status2 = enum<ArrivalStatus> 1
printfn $"Arrival Status: {status2} ({status2:D})"
// The example displays the following output:
// Arrival Status: Early (1)
let status2 = enum<ArrivalStatus> 1
printfn $"Arrival Status: {status2} ({status2:D})"
// The example displays the following output:
// Arrival Status: Early (1)
Dim status2 As ArrivalStatus = CType(1, ArrivalStatus) Console.WriteLine("Arrival Status: {0} ({0:D})", status2) ' The example displays the following output: ' Arrival Status: Early (1)
By calling its implicit parameterless constructor. As the following example shows, in this case the underlying value of the enumeration instance is 0. However, this is not necessarily the value of a valid constant in the enumeration.
ArrivalStatus status1 = new ArrivalStatus();
Console.WriteLine("Arrival Status: {0} ({0:D})", status1);
// The example displays the following output:
// Arrival Status: OnTime (0)
ArrivalStatus status1 = new ArrivalStatus();
Console.WriteLine("Arrival Status: {0} ({0:D})", status1);
// The example displays the following output:
// Arrival Status: OnTime (0)
let status1 = ArrivalStatus()
printfn $ "Arrival Status: {status1} ({status1:D})"
// The example displays the following output:
// Arrival Status: OnTime (0)
let status1 = ArrivalStatus()
printfn $"Arrival Status: {status1} ({status1:D})"
// The example displays the following output:
// Arrival Status: OnTime (0)
Dim status1 As New ArrivalStatus() Console.WriteLine("Arrival Status: {0} ({0:D})", status1) ' The example displays the following output: ' Arrival Status: OnTime (0)
You can call the GetNames method to retrieve a string array containing the names of the enumeration members. Next, for each element of the string array, you can call the Parse method to convert the string to its equivalent enumeration value. The following example illustrates this approach.
string[] names = Enum.GetNames(typeof(ArrivalStatus));
Console.WriteLine("Members of {0}:", typeof(ArrivalStatus).Name);
Array.Sort(names);
foreach(var name in names) {
ArrivalStatus status = (ArrivalStatus) Enum.Parse(typeof(ArrivalStatus), name);
Console.WriteLine(" {0} ({0:D})", status);
}
// The example displays the following output:
// Members of ArrivalStatus:
// Early (1)
// Late (-1)
// OnTime (0)
// Unknown (-3)
let names = Enum.GetNames typeof<ArrivalStatus>
printfn $"Members of {nameof ArrivalStatus}:"
let names = Array.sort names
for name in names do
let status = Enum.Parse(typeof<ArrivalStatus>, name) :?> ArrivalStatus
printfn $" {status} ({status:D})"
// The example displays the following output:
// Members of ArrivalStatus:
// Early (1)
// Late (-1)
// OnTime (0)
// Unknown (-3)
You can call the GetValues method to retrieve an array that contains the underlying values in the enumeration. Next, for each element of the array, you can call the ToObject method to convert the integer to its equivalent enumeration value. The following example illustrates this approach.
var values = Enum.GetValues(typeof(ArrivalStatus));
Console.WriteLine("Members of {0}:", typeof(ArrivalStatus).Name);
foreach(ArrivalStatus status in values) {
Console.WriteLine(" {0} ({0:D})", status);
}
// The example displays the following output:
// Members of ArrivalStatus:
// OnTime (0)
// Early (1)
// Unknown (-3)
// Late (-1)
let values = Enum.GetValues typeof<ArrivalStatus>
printfn $"Members of {nameof ArrivalStatus}:"
for status in values do
printfn $" {status} ({status:D})"
// The example displays the following output:
// Members of ArrivalStatus:
// OnTime (0)
// Early (1)
// Unknown (-3)
// Late (-1)
A convenient way to test whether a flag is set in a numeric value is to call the instance HasFlag method, as shown in the following example.
Pets familyPets = Pets.Dog | Pets.Cat;
if (familyPets.HasFlag(Pets.Dog))
Console.WriteLine("The family has a dog.");
// The example displays the following output:
// The family has a dog.
Pets familyPets = Pets.Dog | Pets.Cat;
if (familyPets.HasFlag(Pets.Dog))
Console.WriteLine("The family has a dog.");
// The example displays the following output:
// The family has a dog.
let familyPets = Pets.Dog || | Pets.Cat
if familyPets.HasFlag Pets.Dog then
printfn "The family has a dog."
// The example displays the following output:
// The family has a dog.
let familyPets = Pets.Dog ||| Pets.Cat
if familyPets.HasFlag Pets.Dog then
printfn "The family has a dog."
// The example displays the following output:
// The family has a dog.
Dim familyPets As Pets = Pets.Dog Or Pets.Cat If familyPets.HasFlag(Pets.Dog) Then Console.WriteLine("The family has a dog.") End If ' The example displays the following output: ' The family has a dog.
let familyPets = Pets.Dog || | Pets.Cat
if (familyPets && & Pets.Dog) = Pets.Dog then
printfn "The family has a dog."
// The example displays the following output:
// The family has a dog.
Use None
as the name of the flag enumerated constant whose value is zero. You cannot use the None
enumerated constant in a bitwise AND operation to test for a flag because the result is always zero. However, you can perform a logical, not a bitwise, comparison between the numeric value and the None
enumerated constant to determine whether any bits in the numeric value are set. This is illustrated in the following example.
Pets familyPets = Pets.Dog | Pets.Cat;
if (familyPets == Pets.None)
Console.WriteLine("The family has no pets.");
else
Console.WriteLine("The family has pets.");
// The example displays the following output:
// The family has pets.
let familyPets = Pets.Dog || | Pets.Cat
if familyPets = Pets.None then
printfn "The family has no pets."
else
printfn "The family has pets."
// The example displays the following output:
// The family has pets.