Java Object Oriented Design — Java Enum Types
An enum type creates an ordered list of constants as a type. It specifies constants in a specific order.
The constants defined in an enum type are instances of that enum type.
Syntax
You define an enum type using the keyword enum with the following syntax:
is the same as the access modifier for a class: public, private, protected, or package-level.
is a valid Java identifier.
The body of the enum type is placed within braces following its name, The body can have a list of comma-separated constants and other elements, for example, instance variables, methods, etc.
Most of the time, the enum body includes only constants.
Example
The following code declares an enum type called Gender, which declares two constants, MALE and FEMALE:
It is a convention to name the enum constants in uppercase.
The following code declares a public enum type called Level with four enum constants: LOW, MEDIUM, HIGH, and URGENT.
A public enum type can be accessed from anywhere in the application.
A public enum type stays in a file with enum type name. The Level enum would be saved in a file named Level.java.
We need to place an enum type in a package and we can use an import statement to import an enum type.
enum variable
We can declare a variable of an enum type the same way we declare a variable of a class type.
The following code declare errorLevel variable of the Level enum type
You can assign null to an enum type variable, like so:
Using Enum Types in switch Statements
You can use enum types in switch statements.
When the switch expression is of an enum type, all case labels must be unqualified enum constants of the same enum type.
enum Direction /* ww w . j a v a 2 s . c o m*/ East, South, West, North > public class Main < public static void main(String args[]) < Direction dir = Direction.South; switch (dir) < case South: System.out.println("south"); break; case East: System.out.println("East"); break; case West: System.out.println("West"); break; case North: System.out.println("North."); break; > > >
The code above generates the following result.
Nested Enum Types
We can have a nested enum type declaration inside a class, an interface, or another enum type.
Nested enum types are implicitly static. Since an enum type is always static, we cannot declare a local enum type inside a method’s body.
We can use any of the access modifiers (public, private, protected, or package) level for a nested enum type.
The following code shows how to declare a nested public enum type named Gender inside a Person class.
class Person < public enum Gender < MALE, FEMALE >> public class Main < public static void main(String[] args) < Person.Gender m = Person.Gender.MALE; Person.Gender f = Person.Gender.FEMALE; System.out.println(m); System.out.println(f); >>
The Person.Gender enum type can be accessed from anywhere in the application because it has been declared public.
We can also use the simple name of an enum constant by importing the enum constants using static imports.
import static com.java2s.enums.Person.Gender.*;
Implementing an Interface to an Enum Type
An enum type may implement interfaces. The rules for an enum type implementing an interface are the same as the rules for a class implementing an interface.
The following code shows how to let enum type implement an interface.
interface Command < void execute(); >/*from w w w. j av a 2 s. c om*/ enum Level implements Command < LOW < public void execute() < System.out.println("Low. "); > >, HIGH < public void execute() < System.out.println("HIGH. "); > >; public abstract void execute(); > public class Main < public static void main(String. args) < for (Command cmd : Level.values()) < cmd.execute(); >> >
The code above generates the following result.
- Next »
- « Previous
java2s.com | © Demo Source and Support. All rights reserved.
Nested Enum in Java
A class that can be defined within another class is called a nested class in Java. You can logically group classes that are used onlyin one place. This makes encapsulation easier to useand makescode easier to read and maintain. The scope of its enclosing class limits a nested class’s scope. So in the following example, the NestedClass class does not exist independently of the OuterClass class.
Members of nested classes (including private members) can access nested classes. However, members of nested classes are not accessible from the outer class. The outer class of a nested class is also a member. As an individual of the containing class, the given class can be pronounced private, public, secure, or bundled-private (the default). There are two types of nested classes:
Nested static class:
A statically nested class is a nested class declared static. Inner circle: Non-static nested class are inner classes.
An inner class object of a regular or regular inner class cannot exist ifan outer class object already exists. In particular, inner-class objects always have a strong connection with outer-class objects. However, for static nested classes, a static nested class object can exist even if theouter class object does not.
Objects of statically nested classes do not strongly connect to objects ofouter classes. Statically nested classes are linked to their enclosing class, like class methods and variables. Like static class methods, statically nested classes cannot directly reference instance variables or methods defined in their enclosing class. It can only be used withobject references. The name of the enclosing class is used to come to them.
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClassnested object =new OuterClass.StaticNestedClass();
// Java program to demonstrate accessing // a static nested class // outer class class OuterClass < // static member static int outer_x = 10; // instance(non-static) member int outer_y = 20; // private member private static int outer_private = 30; // static nested class static class StaticNestedClass < void display() < // can access static member of outer class System.out.println("outer_x = " + outer_x); // can access display private static member of outer class System.out.println("outer_private = " + outer_private); // The following statement will give compilation error // as static nested class cannot directly access non-static members // System.out.println("outer_y wp-block-code">// Java program to demonstrate accessing // a inner class // outer class class OuterClass < // static member static int outer_x = 10; // instance(non-static) member int outer_y = 20; // private member private int outer_private = 30; // inner class class InnerClass < void display() < // can access static member of outer class System.out.println("outer_x = " + outer_x); // can also access non-static member of outer class System.out.println("outer_y = " + outer_y); // can also access a private member of the outer class System.out.println("outer_private wp-block-code">outer_x = 10 outer_y = 20 outer_private = 30
Suppose you need to define a "department code" for each department enumeration constant. This code is alphanumeric, so store it as a string. The department enumeration allows you to create a private instance variable for the department code and a getter method to retrieve its value, just likea class definition. While defining the enumeration itself, wealso define a constructor that we pass in the department code.
The improved enumeration looks like this: It uses a constructor that accepts a department code when creating the enum, a getter method for deptCode called getDeptCode(), and a new private instance variable called deptCode that holds the department code.
public enum Department < HR("DEPT-01"), OPERATIONS("DEPT-02"), LEGAL("DEPT-03"), MARKETING("DEPT-04");//semi-colon is no longer optional here Department(String deptCode)< this.deptCode=deptCode; >private String deptCode; public String getDeptCode() < return deptCode; >>