0

As Java provides a facility for overriding methods of an enumeration as follows:

public enum MyEnum{

    ONE{
        @Override
        public void m(){ //do some }
    },
    TWO{
        @Override
        public void m(){ //do another somesome }
    };

    public abstract void m();
}

I would like to understand where it's really good to use this facility. At the first glance, It seems to be a not good decision to use such overriding ever. But in some cases it may be really convinient to do so.

My question is this:

When it's really good to use the overriding in enumerations?

For instance, in the project, I've used such a way for the enumeration consisiting of 21 enumerators. When I start to do a feature I had only one method overriden in the enumeration, but now I have 8. So, I have the enumeration consisting of 21 enumerators any of them contains 8 overriding of the abstract methods. And it's getting harder to read the enumeration.

So, now I'm not sure about if I should use it in the project ever...

What the facility has been introduced for in Java? Maybe there're some special use-cases.

user3663882
  • 6,957
  • 10
  • 51
  • 92
  • you can search `constant-specific method` in enums and their usecases. – Prashant May 31 '15 at 07:50
  • 2
    Your question is a bit strange. You start by saying that you don't understand why this would be useful. But then you're saying you used it for 8 different methods in a single enum. So you actually found 8 cases where it **is** useful. And then you ask us why you should use that feature. You already have 8 reasons to use it, don't you? – JB Nizet May 31 '15 at 07:55
  • @JBNizet Do you yourself use this? – user3663882 May 31 '15 at 07:57
  • 1
    Yes, I use this feature. It's good old polymorphism. – JB Nizet May 31 '15 at 08:00
  • @JBNizet Let me ask you a few more questions about this. I presume that it works in the way as in my example `ONE` and `TWO` are instances of anonymous subclasses, Is that right? So, as far as I understood from the duplicated topic, the only right way to use it is a finite state machine. Do you use it in something else cases? – user3663882 May 31 '15 at 08:06
  • I don't think I've ever used it to implement a finite state machine. I use it when I need to do something that depends on the enum, just as I would do with any other class designed for inheritance. See https://gist.github.com/jnizet/66e22699000f31569c2a for example. – JB Nizet May 31 '15 at 08:18
  • @JBNizet got that, thank you. – user3663882 May 31 '15 at 08:35

0 Answers0