I want to create a class that would provide me with a card i.e
Card c = new Card(1) // where the builder should get values 1 to 4, representing 1=spade, 2=heart, 3=diamond, 4=clubs
c.getType() // spade
I want the class to check during compilation time whether the card is of type spade, heart, diamond or club, and if not - it'll raise an error and won't let me compile. The class should NOT use enum
Edit: This question is asked solely for the purpose of understanding how would one answer that kind of question in the pre-enum era. I was asked this question during a job interview a couple of years ago
Update: there is no good way to enforce the value being between 1 and 4 (perhaps using some custom complex compile time annotation would work but I doubt it) as has been pointed out. This is just one way to enforce not allowing
Cardto be instantiated without using enums, and it implicitly keeps thevaluebetween 1 and 4 since each subclass sets its own value.One way would be to make
Cardabstract (could also use an interface):Then create child classes for each type:
This would throw a compile time error if someone tried to create a
Carddirectly:Before enums existed, this is how most Java code handled enumerations: using a preset list of integers that were very error prone and not easily enforceable. It was a dark time, let's not go back :)