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

117
Visualizações
How do you create a class of enums without a instance variable?

I have a class with a list of enums, The enums are passed to a constructor and updated to the toString, but I am not allowed to have an instance variable on the class (part of the requirement). How can I make the enums output like the String without adding an instance?

public enum Other {

    GAME_BOY("Game Boy"), MACBOOK("Macbook Pro"), IPHONE("iPhone XS"), LAPTOP("Laptop");

    private final String product; //can't have instance variable

    private Other(String passed) {
        this.product = passed;
    }

    @Override
    public String toString() {
        return product;
    }
}
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You can override toString() for each element:

public enum Other {
   GAME_BOY {
     @Override public String toString() { return "Game Boy"; }
   },
   MACBOOK { ... },
   ...
}

See this code run live at IdeOne.com.

over 4 years ago · Santiago Trujillo Relatório

0

Alternatively, you can put a switch statement in the toString method:

@Override
public String toString() {
    switch (this) {
        case GAME_BOY:
            return "Game boy";
        case MACBOOK:
            return "Macbook Pro";
        ...
    }
}
over 4 years ago · Santiago Trujillo Relatório

0

How about the following:-

public enum Other {

    GAME_BOY, MACBOOK, IPHONE, LAPTOP;

  @Override
  public String toString() {

    switch(this) {
      case GAME_BOY:
        return "Game Boy";

      case MACBOOK:
        return "Macbook Pro";

      case IPHONE:
        return "iPhone XS";

      case LAPTOP:
        return "Laptop";

      default:
        return null;
      }
   }

  public static void main(String[] args) {

    System.out.println("The value of the other is " + Other.GAME_BOY.toString());
  }
}

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