Java

Ibrahim Adeosun
Ibrahim Adeosun
615 Points

How to set an attribute of an object to only accept a number of values

So in java the boolean primitive data type can only hold two values : true or false. So now I want to make a class that has an attribute such as gender, and it will only allow two values. Is that possible

1 Answer

Steve Hunter
MOD
Steve Hunter
Treehouse Moderator 56,736 Points

Hi there,

Yes! Have a read around the enum, for example here.

Or just an if statement. Something like:

String gender; // could be passed into a method too
if (gender.equals("Male") || gender.equals("Female")){
  console.printf("gender set as %s", gender);
} else {
  console.printf("%s is an invalid value - try again", gender);
}

There are probably other ways too. The enum is the more elegant, in my view.

Hope that helps,

Steve.