When declaring an enum inside a class in java I've seen these 2 approaches:
1)
public class MyClass {
private enum MyEnum {
A, B, C;
}
/* Static fields */
/* Instance variables */
/* Methods */
}
2)
public class MyClass {
/* Static fields */
/* Instance variables */
/* Methods */
private enum MyEnum {
A, B, C;
}
}
Which one is the most used? Is there any convention for this?
Enum FieldsThe enum constructor must be private . You cannot use public or protected constructors for a Java enum . If you do not specify an access modifier the enum constructor it will be implicitly private .
Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.
You cannot declare an enumeration within a method. To specify the appropriate level of access, use Private , Protected , Friend , or Public . An Enum type has a name, an underlying type, and a set of fields, each representing a constant.
An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).
Generally in Java, nested data types (e.g. classes, enums) go at the bottom of a file.
However, for short, private enums like the one you posted (which feel more like fields), I'd go with #1.
For longer enums, I'd either go with #2 or put them in a separate file.
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