how to declare the possible values of an attribute in java

338 Views Asked by At

My class must have an attribute of type string which can have just four values :

value1, value2, value3, or value4 ; 

How it can be done in java ?

2

There are 2 best solutions below

0
On BEST ANSWER

Use enumerated types, for example

public enum MyStringType {
  value1{
      public String toString() {
          return "this is value1";
      }
  },

  value2{
      public String toString() {
          return "this is value2";
      }
  }
 /* etc etc */
}
0
On

It can be done a few different ways. This is the most direct (and probably ugly) way to do it, because you only have four eventualities.

 private String someString;

  public void setSomeString(String inString){
     if(inString.equals("valueOne") || 
        inString.equals("valueTwo") || 
        inString.equals("valueThree")||
        inString.equals("valueFour"){

        someString = inString;

 }else{

     //handle this here

   }