Extending a enum in Java

后端 未结 4 1658
迷失自我
迷失自我 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: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).

提交回复
热议问题