Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

158
Visualizações
extending an abstract class with generic enum type

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);
    
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

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();
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda