How to add common methods for a few Java enums? (abstract class ancestor?)

后端 未结 5 729
孤街浪徒
孤街浪徒 2021-01-04 07:01

I have a few Java enums as such

public enum Aggregation
{
    MORTGAGE( \"Mortgage\" ),
    POOLS( \"Pools\" ),
    PORTFOLIO( \"Portfolio\" );

    private         


        
5条回答
  •  忘掉有多难
    2021-01-04 07:33

    You can achieve this with Java 8 default interface methods:

    public class test
    {
        public static void main (String[] arguments) throws Exception
        {
            X.A.foo ();
            Y.B.foo ();
        }
    }
    
    interface MyEnumInterface
    {
        String getCommonMessage ();
        String name ();
    
        default void foo ()
        {
            System.out.println (getCommonMessage () + ", named " + name ());
        }
    }
    
    enum X implements MyEnumInterface
    {
        A, B;
    
        @Override
        public String getCommonMessage ()
        {
            return "I'm an X";
        }
    }
    
    enum Y implements MyEnumInterface
    {
        A, B;
    
        @Override
        public String getCommonMessage ()
        {
            return "I'm an Y";
        }
    }
    

    Note that the interface doesn't know it will be implemented by enums, so it cannot use Enum methods on this in the default methods. However, you may include those methods in the interface itself (like I did with name()) and then use them normally. They will be "implemented" for you by Enum when you declare an enumeration.

提交回复
热议问题