0

I want to create a class that define a string variable which can have only few predefined value.

public class Constraint{                 
     String const; // I want this constraint value to be fixed to either of {greaterthan,lesserthan,greaterthanequalto or lesserthanequalto}
     public Constraint(String const){
               this.const = const;
      }
}

Program should throw an error if any other value is sent. I wan to use something like enum over here, but i want to do so for Strings.

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
shubham gupta
  • 321
  • 3
  • 9
  • 23
  • 1
    You can't but you can use an `enum` instead. [Check this](http://stackoverflow.com/questions/4709175/what-are-enums-and-why-are-they-useful) – Jordi Castilla Jan 19 '17 at 08:26

1 Answers1

6

The concept you are looking for is called Enum.

Simply do not try to re-invent a less powerful, less "standard" workaround.

Seriously: enums give you compile time safety. Use them.

The alternative would be that your "constant" class contains a final, fixed Set of "valid" strings; and you simply check in your "setter" that incoming strings are listed in that Set. And of course, you should make sure that users of your constant class can access the content of that Set, so they can "know" those valid strings when they need to.

GhostCat
  • 137,827
  • 25
  • 176
  • 248