English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

How does Java call another enum value in the constructor of an enum?

An enum (enum) in Java is a data type that stores a set of constant values. You can use enums to store fixed values, such as days of the week, months of the year, etc.

You can use the keyword enum definedenumeration,followed byEnumeration The name of-

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

Methods and variables in enumerations

Enumerations are similar to classes and can contain variables, methods (only concrete methods), and constructors.

Assuming the element values in the enumeration are-

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

To define a constructor, first declare an instance variable to save the value of the element.

private int price;

Then, declare a parameterized constructor to initialize the instance variables created above.

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

Initialize an enumeration with a value from another

Initialize an enumeration with the value of another enumeration.

  • Declare the required enumeration as an instance variable.

  • Initialize it using 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), Bangalore(State.Karnataka), Vishakhapatnam(State.Andhrapradesh);
   //Instance variable
   private State state;
   //Constructor initializes instance variables
   Cities(State state) {
      this.state = state;
   }
   //Display country/Static method of regions
   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 enumeration
      Cities.display(model);
   }
}

Output Result

Value of constants:
0: Hyderabad
1: Delhi
2: Chennai
3: Bangalore
4: Vishakhapatnam
Select one model:
2
State of: Chennai is Tamilnadu

You May Also Like