[ACCEPTED]-Extending a enum in Java-enums

Accepted answer
Score: 55

You can't.

Enum types are final by design.

The 8 reason is that each enum type should have 7 only the elements declared in the enum (as we can use them in a switch statement, for 6 example), and this is not possible if you 5 allow extending the type.

You might do something 4 like this:

public interface MyInterface {
    // add all methods needed here
}

public enum A implements MyInterface {
    A, B;
    // implement the methods of MyInterface
}

public enum B implements MyInterface {
    C;
    // implement the methods of MyInterface
}

Note that it is not possible to 3 do a switch with this interface, then. (Or in 2 general have a switch with an object which could 1 come from more than one enum).

Score: 18

You can implement a common interface

interface I { }

enum A implements I {
   A, B
}
enum B implements I {
   C
}
public void functionA(I i) {
    //do something
}

obj.functionA(A.A);
obj.functionA(B.C);

0

Score: 6

You cannot make Enums extend other Enums, but 11 you can declare an interface which all your 10 Enums can implement. The interface will 9 have to include any methods you expect to 8 invoke on your Enum values. Here is an example:

public class Question6511453 {
    public static void main(String[] args) {
        System.out.println(functionFoo(EnumA.FirstElem));
        System.out.println(functionFoo(EnumA.SecondElem));
        System.out.println(functionFoo(EnumB.ThirdElem));
    }

    private interface MyEnums {
        int ordinal();
    }

    private enum EnumA implements MyEnums {
        FirstElem,
        SecondElem
    }

    private enum EnumB implements MyEnums {
        ThirdElem
    }

    private static int functionFoo(MyEnums enumeration) {
        return enumeration.ordinal();
    }
}

The 7 only problem with this solution is that 6 it takes away your ability to use the Enum 5 as you normally would like in switch statements, because 4 the ordinals and values may not be unique 3 anymore.

This should answer your question, but 2 I doubt it will actually help you with your 1 problem. :(

Score: 4

You should add item C to your enum A. If 3 it's something unrelated and adding it doesn't 2 make sense, functionA() probably shouldn't 1 be the one to handle it.

More Related questions