Can enums be subclassed to add new elements?

前端 未结 15 2058
臣服心动
臣服心动 2020-11-22 12:02

I want to take an existing enum and add more elements to it as follows:

enum A {a,b,c}

enum B extends A {d}

/*B is {a,b,c,d}*/

Is this po

15条回答
  •  梦谈多话
    2020-11-22 12:36

    My way to code that would be as follows:

    // enum A { a, b, c }
    static final Set enumA = new LinkedHashSet<>(Arrays.asList(new Short[]{'a','b','c'}));
    
    // enum B extends A { d }
    static final Set enumB = new LinkedHashSet<>(enumA);
    static {
        enumB.add((short) 'd');
        // If you have to add more elements:
        // enumB.addAll(Arrays.asList(new Short[]{ 'e', 'f', 'g', '♯', '♭' }));
    }
    

    LinkedHashSet provides both that each entry only exists once, and that their order is preserved. If order doesn’t matter, you can use HashSet instead. The following code is not possible in Java:

    for (A a : B.values()) { // enum B extends A { d }
        switch (a) {
            case a:
            case b:
            case c:
                System.out.println("Value is: " + a.toString());
            break;
            default:
                throw new IllegalStateException("This should never happen.");
        }
    }
    

    The code can be written as follows:

    for (Short a : enumB) {
        switch (a) {
            case 'a':
            case 'b':
            case 'c':
                System.out.println("Value is: " + new String(Character.toChars(a)));
            break;
            default:
                throw new IllegalStateException("This should never happen.");
        }
    }
    

    From Java 7 onwards you can even do the same with String:

    // enum A { BACKWARDS, FOREWARDS, STANDING }
    static final Set enumA = new LinkedHashSet<>(Arrays.asList(new String[] {
            "BACKWARDS", "FOREWARDS", "STANDING" }));
    
    // enum B extends A { JUMP }
    static final Set enumB = new LinkedHashSet<>(enumA);
    static {
        enumB.add("JUMP");
    }
    

    Using the enum replacement:

    for (String a : enumB) {
        switch (a) {
            case "BACKWARDS":
            case "FOREWARDS":
            case "STANDING":
                System.out.println("Value is: " + a);
            break;
            default:
                throw new IllegalStateException("This should never happen.");
        }
    }
    

提交回复
热议问题