Extending a enum in Java

后端 未结 4 1630
迷失自我
迷失自我 2021-01-01 10:44

I have an enum, let\'s call it A:

public enum A
{
    A,
    B
}

I have a function that takes an enum A:

public void functi         


        
相关标签:
4条回答
  • 2021-01-01 11:28

    You cannot make Enums extend other Enums, but you can declare an interface which all your Enums can implement. The interface will have to include any methods you expect to 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 only problem with this solution is that it takes away your ability to use the Enum as you normally would like in switch statements, because the ordinals and values may not be unique anymore.

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

    0 讨论(0)
  • 2021-01-01 11:36

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

    0 讨论(0)
  • 2021-01-01 11:41

    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 讨论(0)
  • 2021-01-01 11:46

    You can't.

    Enum types are final by design.

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

    You might do something 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 do a switch with this interface, then. (Or in general have a switch with an object which could come from more than one enum).

    0 讨论(0)
提交回复
热议问题