0

Is there a way to extend an abstract class with generic enum types? When I extend it and implement myMethod below, only the method from the abstract class gets called.

  1. first i define abstract class with method myMethod where i would like to make decisions based on the enum value.

    public abstract class MyAbstractClass <T extends enum<T>> {
    
        public void myMethod(T cmd) {
          //i want to override this
        }
    
        public void update(T cmd) {
          myMethod(cmd);
        }
    }
    
  2. define an enum and extend the class, but the child class myMethod never gets called(only the myMethod of abstract class gets called).

    enum CMD {
       CMD_1, CMD_2
    }
    
    public class Child extends MyAbstractClass<CMD> {
    ...
      public void myMethod(CMD cmd) {
        if (cmd == CMD_1) { //do something }
      }
    ...
    }
    
  3. instantiate and call

    Child child = new Child();
    child.update(CMD.CMD_1);
    
prostock
  • 9,327
  • 19
  • 70
  • 118

2 Answers2

1

Yes. Use T extends Enum<T>:

public abstract class MyAbstractClass <T extends Enum<T>> {
    public void myMethod(T cmd) {}
}

See live demo of your code, with this change, compiling OK.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • thx for getting back, but my initial post wasn't too clear so i edited it. actually my issue is when i extend the abstract class and try to use CMD to make a decision on actions to perform. myMethod, which i override, never gets called. instead the parent implementation gets called. – prostock Apr 29 '17 at 11:41
  • 1
    @prostock the overridden method *does* get called. See updated link with demo code proving this. – Bohemian Apr 29 '17 at 11:59
0

If you want to select the behaviour according to the enum value, then one way to do it is to put the behaviour into each enum value, e.g.:

enum Command {
    CMD1 {
        @Override
        void execute() {
            System.out.println("Command.CMD1");
        }
    },
    CMD2 {
        @Override
        void execute() {
            System.out.println("Command.CMD2");
        }
    };

    abstract void execute();
}

public static void main(String[] args) {
    final Command cmd = Command.CMD1;

    cmd.execute();
}
jon hanson
  • 8,722
  • 2
  • 37
  • 61