Some Important points about Java Enums.
- Enums can be declared as their own separate class, or as a class member, however they must not be declared within a method.
- Enums can be declared outside the class.
- Enums cannot be private or protected.
- Enums can have only default or public modifier.
- Semicolon at the end of Enums declaration is optional.
- Enum is a special type of Class.
- Enum constructor are never invoked directly
- Enum constructor can be overloaded just like any other constructor in class.
- If an enum is declared as public then it should be declared in its own file.
- Enums declared within a class can have public, private, protected, default, static and abstract modifiers
package TechnicalTutorial;
/* Enum declared outside the class can have default access only */
enum TechEnum{
FIRST, SECOND, THIRD
}
public class Example_1 {
public enum TechEnum_2{
HUNDRED, THOUSAND
}
public static void main(String[] args) {
TechEnum num = TechEnum.FIRST;
System.out.println(num);
}
}
/* Enum declared outside the class can have default access only */
enum TechEnum{
FIRST, SECOND, THIRD
}
public class Example_1 {
public enum TechEnum_2{
HUNDRED, THOUSAND
}
public static void main(String[] args) {
TechEnum num = TechEnum.FIRST;
System.out.println(num);
}
}
In above example enum can be declared as public only within a Class i.e. TechEnum_2 . If an enum need to be declared as public outside the class then it should be created in separate file.