Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 class AClass {

    private enum MyEnum{
        A { public String method1(){ return null; } },
        B { public Object method2(String s){ return null; } },
        C { public void method3(){ return null; } } ;
    }

    ...
}

I was surprised that this is even possible, do this "exclusive methods" specific to each instance have a name to look for documentation?

Also, how is it supposed to be used? Because the next is not compiling:

    private void myMethod () {
        MyEnum.A.method1();
    }

How am I supposed to use these "exclusive" methods?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
237 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...