2

In order to offer specific behavior to each instance of an enum for a common public method we could do the following:

public enum Action { 
    a{
        void doAction(...){
            // some code
        }

    }, 
    b{
        void doAction(...){
            // some code
        }

    }, 
    c{
        void doAction(...){
            // some code
        }

    };

    abstract void doAction (...);
}

Is there any way of giving specific implementation to an abstract generic method defined in an enum?

E.g.:

abstract<T> T doAction (T t);

I read in other questions that it shouldn't be possible, but I've been struggling for workarounds and came up with overly complicated contraptions. Maybe generics aren't the right way. Is there an easier way to achieve this?

Cristina_eGold
  • 1,463
  • 2
  • 22
  • 41
  • I'm not sure I understand what you're trying to achieve. Please define "giving specific implementation to an abstract generic method". – Thomas Apr 24 '15 at 10:44
  • 1
    Why do you need this? If constant `A` has a method that accepts a `String` and constant `B` has a method that accepts an `Integer` why do they need to be the same method? – Paul Boddington Apr 24 '15 at 10:44
  • Possibly related: http://stackoverflow.com/q/28234960/2891664 – Radiodef Apr 24 '15 at 11:01

1 Answers1

4

Yes, you can do it. Just leave the abstract method definition as it is and in each of the enum constants, you have to do something like:

a{
    @Override
    <T> T doAction(T t) {
        //your implementation
    }
}...

However, please note that the T type-parameter in the a constant is not the same as the T type parameter for the b constant and so on.

When done, you can use it like this:

String string = Action.a.<String>doAction("hello");

or

Integer integer = Action.b.<Integer>doAction(1);

Explicitly providing the type here is completely optional, as the compiler will infer the resulting type by the type of the provided argument.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147