What are enums and why are they useful?

后端 未结 27 1816
一整个雨季
一整个雨季 2020-11-22 07:06

Today I was browsing through some questions on this site and I found a mention of an enum being used in singleton pattern about purported thread safety benefits

27条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 07:30

    What is an enum

    • enum is a keyword defined for Enumeration a new data type. Typesafe enumerations should be used liberally. In particular, they are a robust alternative to the simple String or int constants used in much older APIs to represent sets of related items.

    Why to use enum

    • enums are implicitly final subclasses of java.lang.Enum
    • if an enum is a member of a class, it's implicitly static
    • new can never be used with an enum, even within the enum type itself
    • name and valueOf simply use the text of the enum constants, while toString may be overridden to provide any content, if desired
    • for enum constants, equals and == amount to the same thing, and can be used interchangeably
    • enum constants are implicitly public static final

    Note

    • enums cannot extend any class.
    • An enum cannot be a superclass.
    • the order of appearance of enum constants is called their "natural order", and defines the order used by other items as well: compareTo, iteration order of values, EnumSet, EnumSet.range.
    • An enumeration can have constructors, static and instance blocks, variables, and methods but cannot have abstract methods.

提交回复
热议问题