Reputation: 23
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
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