3

I am very new to Java-programming, and have some problems in getting an enumerated type to work. In my program I have declared the following static variables:

class Employee {

enum Gender {MALE, FEMALE};
static final double NORMAL_WORK_WEEK = 37.5;
static int numberOfFemales;
static int numberOfMales;
Gender sex;
}

I have added a method for printing relevant information, as well as the following method:

static void registerEmployeeGender(Gender sex) {
switch(sex) {
case MALE:
numberOfMales++; break;
case FEMALE:
numberOfFemales++; break;}
}

In my client where I attemt to run the program, I am unable to use this last method. Say I create an object, Employee1, and type:

Employee1.registerEmployeeGender(FEMALE);

I then get the error message: FEMALE cannot be resolved to a variable.

What is causing this error message? Like I said, I am quite new to Java, and this is my first attempt at using the enumerated type, so I probably have done something wrong. If anyone can give me any help, I would greatly appreciate it.

Of course, I have only posted part of the program here, but this is the only part that is giving me an error message. If you need me to post more of the program, or all of it for that matter, please let me know.

Thanks in advance for any help!

reggie
  • 13,313
  • 13
  • 41
  • 57
Kristian
  • 1,239
  • 12
  • 31
  • 44

3 Answers3

7

use

Employee1.registerEmployeeGender(Gender.FEMALE);

and make sure that u make the following import statement in your code

import static com.example.Employee.Gender.*;
confucius
  • 13,127
  • 10
  • 47
  • 66
  • The 2nd phrase which you hastily copied from my answer is however not really applicable on the example which you initially proposed. You do **not** need to `static import` it whenever you're already specifying the enum name. – BalusC Sep 07 '11 at 19:59
  • His answer arrived 2 minutes before yours. How could he have copied it? – bos Oct 28 '11 at 12:04
5

You need to static import the enum values in order to be able to use them statically the way as you presented:

import static com.example.Employee.Gender.*;

The normal practice, however, is to just import the enum

import com.example.Employee.Gender;

and specify the enum name as well:

Employee1.registerEmployeeGender(Gender.FEMALE);
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Good answer. The `import static` part takes away from the real problem, which is that the `enum` instance needs to be qualified – Java Drinker Sep 07 '11 at 19:52
1

To access the enum items use it like this "Gender.FEMALE"

This might help you more.

franklins
  • 3,710
  • 6
  • 41
  • 56
  • Thank you very much! I simply forgot to add the Gender. before FEMALE like you point out! I appreciate your help! – Kristian Sep 07 '11 at 19:01