victoria
victoria

Reputation: 23

is there a way to declare a variable with limited options?

i'm trying write a variable (e.g. private String colour) but I want it to only be able to be black or white, as in my class diagram I have written it as color:{Black,White}. Is this something I can declare at this stage? If so how is this written?

Upvotes: 2

Views: 572

Answers (2)

czolbe
czolbe

Reputation: 611

Generally, if there are any constraints to be set on a field value, you can consider using Enum, which are a special class/type you can declare your variable to be in order to force it to accept a certain range of constant values. For your case,

Create an enum:

public enum Colour{
   BLACK,
   WHITE
}

Declarethe colour field like so:

private Colour productColour;

Assigning of value will look like this:

productColour = Colour.BLACK;

Upvotes: 7

Renato
Renato

Reputation: 2157

Use Enum. For example:

public enum Color{
 WHITE, BLACK;
}

More info here

Upvotes: 7

Related Questions