Home > database >  Java enum declaration contains members and methods
Java enum declaration contains members and methods

Time:11-15

I came across the following bit of Java code in some open source code shown below (older version of JSoup).

There's a class declaration. And within the class declaration is an enum declared. But the enum appears to be more of a class like declaration with a constructor method, private members, and a public method. The actual enum values declared are getting initialized with a static member of the parent class.

I'm used to vanilla enum declarations, but I haven't seen this syntax or pattern before.

What do you call this pattern, how does it work, and what does it enable?

public class Entities {
    public enum EscapeMode {
        /** Restricted entities suitable for XHTML output: lt, gt, amp, and quot only. */
        xhtml(xhtmlByVal),
        /** Default HTML output entities. */
        base(baseByVal),
        /** Complete HTML entities. */
        extended(fullByVal);

        private Map<Character, String> map;

        EscapeMode(Map<Character, String> map) {
            this.map = map;
        }

        public Map<Character, String> getMap() {
            return map;
        }
    }

    private static final Map<String, Character> full;
    private static final Map<Character, String> xhtmlByVal;
    private static final Map<String, Character> base;
    private static final Map<Character, String> baseByVal;
    private static final Map<Character, String> fullByVal;

    private Entities() {}

    // remaining code not shown for brevity

CodePudding user response:

Enums in Java are just classes, a special kind of class, but still a class.

So, yes, enums can have constructors, member fields, and methods.

Technically, all Java enums are implicitly a subclass of the java.lang.Enum class. This is why an enum cannot extend from a class of your choosing; enums already extend from Enum.

See tutorial by Oracle on enums.

By the way, Java 16 brought a handy new feature for enums: You can declare an enum locally. As part of the work to implement records, we can now declare enums, interfaces, and records locally.

CodePudding user response:

enum in Java is just a class with constants of its type. This means an enum A will contain constants of type A.

This enum EscapeMode has a private data member map and a constructor is made to initialize map. The getter getMap() returns the map.

xhtml, base, and extended are constants separated by a comma and terminated with a semicolon. As they are objects of EscapeMode, you need to pass a Map object to the constructor to initialize them. xhtmlByVal is passed to the constructor to initialize xhtml, and so on.

This feature brings properties and behaviors to enum objects. Enums are just like any other class but inherit the java.lang.Enum class

  •  Tags:  
  • java
  • Related