Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda