Enums: methods exclusive to each one of the instances

前端 未结 3 1027
有刺的猬
有刺的猬 2020-12-18 19:01

From another question I have learnt that it is possible in Java to define specific methods for each one of the instances of an Enum:

public          


        
3条回答
  •  情深已故
    2020-12-18 19:04

    You need to declare abstract methods in your enum which are then implemented in specific enum instances.

    class Outer {
    
        private enum MyEnum {
            X {
                public void calc(Outer o) {
                    // do something
                }
            },
            Y {
                public void calc(Outer o) {
                    // do something different
                    // this code not necessarily the same as X above
                }
            },
            Z {
                public void calc(Outer o) {
                    // do something again different
                    // this code not necessarily the same as X or Y above
                }
            };
    
            // abstract method
            abstract void calc(Outer o);
        }
    
        public void doCalc() {
            for (MyEnum item : MyEnum.values()) {
                item.calc(this);
            }
        }
    }
    

提交回复
热议问题