YouTip LogoYouTip

Java Enum

# Java Enum(enum) | \\n\\n# Java enum \\n\\n# Java Enum(enum)\\n\\nJava Enums are special classes that generally represent a set of constants, such as the 4 seasons of a year, the 12 months of a year, the 7 days of a week, directions like north, south, east, west, etc.\\n\\nJava enum classes use the enum keyword to define, and each constant is separated by a comma.\\n\\nFor example, define a color enum class.\\n\\n```java\\nenum Color { RED, GREEN, BLUE; }\\n\\nThe above enum class Color has color constants RED, GREEN, BLUE, representing red, green, and blue respectively.\\n\\nInstance:\\n\\n## Instance\\n\\n```java\\nenum Color\\n{\\n RED, GREEN, BLUE;\\n}\\n\\npublic class Test \\n{\\n // Execute output result\\n public static void main(String[] args)\\n {\\n Color c1 =Color.RED;\\n System.out.println(c1);\\n }\\n}\\n\\nThe output of the above code is:\\n\\nRED\\n\\n### Using Enums in Inner Classes\\n\\nEnum classes can also be declared in inner classes:\\n\\n## Instance\\n\\n```java\\npublic class Test \\n{\\n enum Color\\n {\\n RED, GREEN, BLUE;\\n }\\n\\n // Execute output result\\n public static void main(String[] args)\\n {\\n Color c1 =Color.RED;\\n System.out.println(c1);\\n }\\n}\\n\\nThe output of the above code is:\\n\\nRED\\n\\nEach enum is implemented internally through Class, and all enum values are public static final.\\n\\nThe above enum class Color is internally implemented as:\\n\\n```java\\nclass Color{ public static final Color RED = new Color(); public static final Color BLUE = new Color(); public static final Color GREEN = new Color();}\\n\\n### Iterating Enum Elements\\n\\nYou can use for statement to iterate enum elements:\\n\\n## Instance\\n\\n```java\\nenum Color\\n{\\n RED, GREEN, BLUE;\\n}\\n\\npublic class MyClass {\\n public static void main(String[] args) \\n {\\n for (Color myVar : Color.values()) {\\n System.out.println(myVar);\\n }\\n }\\n}\\n\\nThe output of the above code is:\\n\\nRED\\nGREEN\\nBLUE\\n\\nThe values() method returns an array of all enum constants.\\n\\n### Enum Methods\\n\\n| Method | Description |\\n|--------|-------------|\\n| values() | Returns an array containing all enum constants in the order they are declared |\\n| valueOf() | Returns the enum constant of the specified type with the specified name |\\n\\n## Instance\\n\\n```java\\nenum Color\\n{\\n RED, GREEN, BLUE;\\n}\\n\\npublic class Test \\n{\\n public static void main(String[] args)\\n {\\n // Call values()\\n Color[] arr = Color.values();\\n\\n // Iterate enum using for-each loop\\n for (Color col: arr)\\n {\\n // Call ordinal() to find index\\n System.out.println(col + " at index " + col.ordinal());\\n }\\n\\n // Use valueOf() to return an enum constant of the specified type with the specified name\\n System.out.println(Color.valueOf("RED"));\\n }\\n}\\n\\nThe output of the above code is:\\n\\nRED at index 0\\nGREEN at index 1\\nBLUE at index 2\\nRED\\n\\n### Comparison of Enum and Class\\n\\nIn terms of functionality, enums can be considered as special classes, which can contain methods and other operations, compared to classes:\\n\\n- Enums cannot inherit other classes\\n- Enums cannot be abstract\\n- Enums cannot use final to modify (automatically considered as final)\\n- But enums can implement one or more interfaces\\n\\n## Enum Construction Method\\n\\nEnum class can have construction methods, but it is private, and you cannot invoke the construction method from outside, nor can you use new to create an enum object. The definition of the construction method must be in the first line of the enum content.\\n\\n## Instance\\n\\n```java\\npublic class Test \\n{\\n enum Color\\n {\\n RED("Red"), GREEN("Green"), BLUE("Blue");\\n private String name;\\n Color(String name)\\n {\\n this.name = name;\\n }\\n public String getName()\\n {\\n return name;\\n }\\n }\\n\\n public static void main(String[] args) \\n {\\n for (Color c: Color.values())\\n {\\n System.out.println(c + " : " + c.getName());\\n }\\n }\\n}\\n\\nThe output of the above code is:\\n\\nRED : Red\\nGREEN : Green\\nBLUE : Blue\\n\\n### Enum Common Scenarios\\n\\nEnum is often used in switch statements:\\n\\n## Instance\\n\\n```java\\nenum Color\\n{\\n RED, GREEN, BLUE;\\n}\\n\\npublic class MyClass {\\n public static void main(String[] args) {\\n Color myVar = Color.BLUE;\\n\\n switch(myVar) {\\n case RED:\\n System.out.println("Selected RED");\\n break;\\n case GREEN:\\n System.out.println("Selected GREEN");\\n break;\\n case BLUE:\\n System.out.println("Selected BLUE");\\n break;\\n }\\n }\\n}\\n\\nThe output of the above code is:\\n\\nSelected BLUE\\n\\n### Enum Class Attributes\\n\\nEnum class has the following attributes:\\n\\n- name(): Returns the name of the enum constant, exactly as declared in the enum type. This method is essentially the same as toString().\\n- ordinal(): Returns the ordinal of the enum constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).\\n- compareTo(): Compares this enum with another object of the same enum type based on the ordinal of the enum.\\n- equals(): Compares this enum with another object for equality.\\n- toString(): Returns the name of the enum constant, as declared in the enum type.\\n- getDeclaringClass(): Returns the Class object corresponding to the enum type of this enum constant.\\n- hashCode(): Returns the hash code of this enum constant.\\n- clone(): Throws CloneNotSupportedException. This ensures that enums are never cloned, preserving the singleton nature of enum.\\n- finalize(): Deprecated. It indicates that enum constants cannot be finalized.\\n\\n## Instance\\n\\n```java\\nenum Color\\n{\\n RED, GREEN, BLUE;\\n}\\n\\npublic class Test \\n{\\n public static void main(String[] args)\\n {\\n Color c1 = Color.RED;\\n System.out.println("name(): " + c1.name());\\n System.out.println("ordinal(): " + c1.ordinal());\\n System.out.println("compareTo(): " + c1.compareTo(Color.GREEN));\\n System.out.println("equals(): " + c1.equals(Color.BLUE));\\n System.out.println("toString(): " + c1.toString());\\n System.out.println("getDeclaringClass(): " + c1.getDeclaringClass());\\n System.out.println("hashCode(): " + c1.hashCode());\\n System.out.println("clone(): " + c1.clone());\\n }\\n}\\n\\nThe output of the above code is:\\n\\nname(): RED\\nordinal(): 0\\ncompareTo(): -1\\nequals(): false\\ntoString(): RED\\ngetDeclaringClass(): class Color\\nhashCode(): 366712642\\nclone(): java.lang.CloneNotSupportedException: Enum not allowed to clone.\\n\\nNote: The clone() method prevents enums from being cloned to ensure that each enum constant is singleton. This is a language-level protection measure to maintain the integrity of the enum.\\n\\nIn the next chapter, we will learn about Java packages (package).
← Java ArraylistJava Anonymous Class β†’