How to call another enum value in an enum's constructor using java?


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

You can define an enumeration using the keyword enum followed by the name of the enumeration as −

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

Methods and variables in an enumeration

Enumerations are similar to classes and, you can have variables, methods (Only concrete methods) and constructors within them.

For suppose we have elements in an enumeration with values as −

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

To define a constructor in it, first of all declare an instance variable to hold the values of the elements.

private int price;

Then, declare a parameterized constructor initializing above created instance variable.

Scoters (int price) {
   this.price = price;
}

Initializing the values of an enum with another

To initialize the enum with values in another enum.

  • Declare the desired enum as the instance variable.
  • Initialize it with a parameterized constructor.

Example

import java.util.Scanner;
enum State{
   Telangana, Delhi, Tamilnadu, Karnataka, Andhrapradesh
}
enum Cities {
   Hyderabad(State.Telangana), Delhi(State.Delhi), Chennai(State.Tamilnadu), Banglore(State.Karnataka), Vishakhapatnam(State.Andhrapradesh);
   //Instance variable
   private State state;
   //Constructor to initialize the instance variable
   Cities(State state) {
      this.state = state;
   }
   //Static method to display the country
   public static void display(int model){
      Cities constants[] = Cities.values();
      System.out.println("State of: "+constants[model]+" is "+constants[model].state);
   }
}
public class EnumerationExample {
   public static void main(String args[]) {
      Cities constants[] = Cities.values();
      System.out.println("Value of constants: ");
      for(Cities d: constants) {
         System.out.println(d.ordinal()+": "+d);
      }
      System.out.println("Select one model: ");
      Scanner sc = new Scanner(System.in);
      int model = sc.nextInt();
      //Calling the static method of the enum
      Cities.display(model);
   }
}

Output

Value of constants:
0: Hyderabad
1: Delhi
2: Chennai
3: Banglore
4: Vishakhapatnam
Select one model:
2
State of: Chennai is Tamilnadu
raja
Published on 05-Aug-2019 14:38:00
Advertisements