Can we create an enum with custom values in java?

Java 8Object Oriented ProgrammingProgramming

Enumeration (enum) in Java is a datatype which stores a set of constant values (Strings in general). You can use enumerations to store fixed values such as days in a week, months in a year etc.

enum Days {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

Custom values to the constants

Instead of declaring just string constants in an enum, you can also have values to these constants as −

enum Vehicles {
   ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000);
}

Whenever, you need to assign custom values to the constants of an enum −

  • To hold the value of each constant you need to have an instance variable (generally, private).
  • You cannot create an object of an enum explicitly so, you need to add a parameterized constructor to initialize the value(s).
  • The initialization should be done only once. Therefore, the constructor must be declared private or default.
  • To returns the values of the constants using an instance method(getter).

Example

In the following Java example, we are defining an enum with name Vehicles and declaring five constants representing the vehicle names with their prices as values.

 Live Demo

enum Vehicles {
   //Constants with values
   ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000);
   //Instance variable
   private int price;
   //Constructor to initialize the instance variable
   Vehicles(int price) {
      this.price = price;
   }
   public int getPrice() {
      return this.price;
   }
}
public class EnumTest{
   public static void main(String args[]) {
      Vehicles vehicles[] = Vehicles.values();
      for(Vehicles veh: vehicles) {
         System.out.println("Price of "+veh+" is: "+veh.getPrice());
      }
   }
}

Output

Price of ACTIVA125 is: 80000
Price of ACTIVA5G is: 70000
Price of ACCESS125 is: 75000
Price of VESPA is: 90000
Price of TVSJUPITER is: 75000
raja
Published on 05-Jul-2019 13:16:15
Advertisements