Java Reference
In-Depth Information
local enum type (e.g. inside a method's body). You can use any of the access modifiers ( public , private , protected ,
or package) level for a nested enum type. Listing 18-7 shows the code that declares a nested public enum type named
Gender inside a Person class.
Listing 18-7. A Gender Enum Type as a Nested Enum Type Inside a Person Class
// Person.java
package com.jdojo.enums;
public class Person {
public enum Gender {MALE, FEMALE}
}
The Person.Gender enum type can be accessed from anywhere in the application because it has been declared
public . You need to import the enum type to use its simple name in other packages, as shown in the following code:
// Test.java
package com.jdojo.enums.pkg1;
import com.jdojo.enums.Person.Gender;
public class Test {
public static void main(String[] args) {
Gender m = Gender.MALE;
Gender f = Gender.FEMALE;
System.out.println(m);
System.out.println(f);
}
}
You can also use the simple name of an enum constant by importing the enum constants using static imports.
The following code snippet uses MALE and FEMALE simple names of constants of Person.Gender enum type. Note that
the first import statement is needed to import the Gender type itself to use its simple name in the code.
// Test.java
package com.jdojo.enums.pkg1;
import com.jdojo.enums.Person.Gender;
import static com.jdojo.enums.Person.Gender.*;
public class Test {
public static void main(String[] args) {
Gender m = MALE;
Gender f = FEMALE;
System.out.println(m);
System.out.println(f);
}
}
Search WWH ::




Custom Search