cs notebook0
  • Introduction
  • Core Java
  • some notes
  • Data structure&algorithm
  • Garbage Collection
  • HashMap
  • Collection0
  • Collection1
  • Collection2
  • comparatorVScomparable
  • exception0
  • exception1
  • exception2
  • Enum in Java
  • JVM
  • Wrapper Classes in Java
  • String, int convert
  • HashSetVSTreeSetVSLinkedHashSet
  • Pair
Powered by GitBook
On this page
  • 1. Important points of enum:
  • 2. Enum and Inheritance:
  • 2.1 values(), ordinal() and valueOf() methods:

Was this helpful?

Enum in Java

Enumerations serve the purpose of representing a group of named constants in a programming language.

Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes, command lines flags, etc. It is not necessary that the set of constants in an enum type stay fixed for all time.

1. Important points of enum:

  • Every enum internally implemented by using Class:

/* internally above enum Color is converted to class Color
{
    public static final Color RED = new Color();
    public static final Color Blue = new Color();
    public static final Color Green = new Color();
}
  • Every enum constant represents an Object of type enum.

  • enum type can be passes as an argument to switch statement.

  • Every enum constant is always implicitly public static final. Since it is static, we can access it by using enum Name. Since it is final, we can't create child enums.

  • We can declare main() method inside enum. Hence we can invoke enum directly from the Command Prompt.

enum Color{
    RED, GREEN, BLUE;
    //driver method
    public static void main(String[] args){
        Color c1 = Color.RED;
        System.out.println(c1);
    }
}

2. Enum and Inheritance:

  • All enums implicitly extend java.lang.Enum class. As a class can only extend one parent in Java, so an enum cannot extend anything else.

  • toString() method is overridden in java.lang.Enum class, which returns enum constant name.

  • enum can implement many interfaces.

2.1 values(), ordinal() and valueOf() methods:

  • These methods are present inside java.lang.Enum

  • values() method can be used to return all values present inside enum.

  • Order is important in enums. By using ordinal() method, each enum constant index can be found, just like array index.

  • valueOf() method returns the enum constant of the specified string value, if exists.

Previousexception2NextJVM

Last updated 5 years ago

Was this helpful?