Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!