Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reaching a variable inside of an enum element in java

Tags:

java

enums

I want each element of an enum to have different variables but I can't reach them.

public class Employee {
public GENERAL[] general = GENERAL.values();

public static void main(String[] args) {
    Employee e = new Employee(); 
    e.general[GENERAL.INCOME.ordinal()].salary = 10; //this line doesn't compile

}

enum GENERAL{
    INCOME{
        public int salary;
        public int tips;
    },SATIFACTION{
        //some variables
    },EFFICIENCY{
        //some variables
    };
}

}

I've tried casting to (GENERAL.INCOME) but it didn't work. Is there a way to do it? If this is not possible, what is the best work around? Thanks in advance.

like image 576
WVrock Avatar asked Nov 19 '25 03:11

WVrock


1 Answers

Try defining variables at enum level rather than individual elements:

  public static void main(String[] args) {
  MainClass e = new MainClass(); 
      e.general[GENERAL.INCOME.ordinal()].salary = 10; //this line doesn't compile
      System.out.println(e.general[GENERAL.INCOME.ordinal()].salary);
  }

  enum GENERAL{
     INCOME(0,0), SATIFACTION(0, 0), EFFICIENCY(0,0);
     int salary;
     int tips;
     GENERAL(int salary, int tips){
         this.salary = salary;
         this.tips = tips;
     }
  }
like image 111
SMA Avatar answered Nov 21 '25 18:11

SMA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!