Enumerations in Java represents a group of named constants, you can create an enumeration using the following syntax
enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.
Example
public class EnumerationExample { enum Enum { Mango, Banana, Orange, Grapes, Thursday, Apple } public static void main(String args[]) { Enum constants[] = Enum.values(); System.out.println("Value of constants: "); for(Enum d: constants) { System.out.println(d); } } }
Output
Value of constants: Mango Banana Orange Grapes Thursday Apple
Example
enum Vehicles { //Declaring the constants of the enum ACTIVA125, ACTIVA5G, ACCESS125, VESPA, TVSJUPITER; int i; //Instance variable Vehicles() { //constructor } public void enumMethod() { //method System.out.println("Current value: "+Vehicles.this); } } public class Sam{ public static void main(String args[]) { Vehicles vehicles[] = Vehicles.values(); for(Vehicles veh: vehicles) { System.out.println(veh); } vehicles[3].enumMethod(); } }
Output
ACTIVA125 ACTIVA5G ACCESS125 VESPA TVSJUPITER Current value: VESPA