Can an enum have abstract methods?

前端 未结 4 641
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 13:11

Can an enum have abstract methods? If so, what is the use, and give a scenario which will illustrate this usage.

4条回答
  •  抹茶落季
    2020-12-05 13:32

    Yes enum can contain abstract method - you can use this approach if you have own implementation per enum constants. (or you can omit using abstract method with using customized value per enum constant Enum with customized value in Java)

    for example (constant-specific method implementations)

    enum TrafficSignal {
    
        RED{
            @Override
            public void action(){
                System.out.println("STOP");
            }
        }, 
        GREEN{
            @Override
            public void action(){
                System.out.println("GO");
            }
        }, 
        ORANGE{
            @Override
            public void action(){
                System.out.println("SLOW DOWN");
            }
        };
    
    
        public abstract void action();
    }
    

    If this method is common for all enum constants then consider using interface. (Java enums extend the java.lang.Enum generic class implicitly, so your enum types cannot extend another class(becouse java does not support multiple inheritance) but can implement interface)

    interface ColorInterface{
        void inLowerCase();
    }
    
    enum Color implements ColorInterface{
    
        RED, GREEN, ORANGE;
    
        @Override
        public void inLowerCase(){
            System.out.println(this.toString().toLowerCase());
        }
    }
    

    Usage:

    public class TestEnums{
    
         public static void main(String []args){
            TrafficSignal signal = TrafficSignal.RED;
            signal.action();
    
            ColorInterface color = Color.RED;
            color.inLowerCase();
         }
    }
    

    Out:

    STOP
    red
    

    Consider the strategy enum pattern if some, but not all, enum constants share common behaviors. [Effective Java - Joshua Bloch - third edition. page 166]

提交回复
热议问题