Difference between revisions of "Enums"
From Suhrid.net Wiki
Jump to navigationJump to search (Created page with "* Enums are a feature that allows a variable to be restricted to having only a few predefined values. * e.g. if we want to restrict a variable that represents t-shirt sizes to on...") |
|||
| Line 5: | Line 5: | ||
enum TShirtSize { | enum TShirtSize { | ||
| − | S, | + | S,M, L, XL |
| − | |||
| − | |||
| − | |||
}; | }; | ||
| + | |||
| + | enum TShirtColor { | ||
| + | RED, BLACK, BLUE, WHITE; | ||
| + | } | ||
| + | |||
| + | public class TShirt { | ||
| + | |||
| + | private TShirtSize size; | ||
| + | private TShirtColor color; | ||
| + | |||
| + | public TShirt(TShirtSize size, TShirtColor color) { | ||
| + | this.size = size; | ||
| + | this.color = color; | ||
| + | } | ||
| + | |||
| + | public String toString() { | ||
| + | return size + "," + color; | ||
| + | } | ||
| + | |||
| + | public static void main(String[] args) { | ||
| + | |||
| + | TShirt t1 = new TShirt(TShirtSize.M, TShirtColor.RED); | ||
| + | System.out.println(t1); //Will print: M, RED; | ||
| + | TShirt t2 = new TShirt(TShirtSize.L, TShirtColor.WHITE); | ||
| + | System.out.println(t2); //Will print: L, WHITE; | ||
| + | } | ||
| + | |||
| + | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Revision as of 21:53, 24 June 2011
- Enums are a feature that allows a variable to be restricted to having only a few predefined values.
- e.g. if we want to restrict a variable that represents t-shirt sizes to only one of four possible sizes, we can use an enum:
enum TShirtSize {
S,M, L, XL
};
enum TShirtColor {
RED, BLACK, BLUE, WHITE;
}
public class TShirt {
private TShirtSize size;
private TShirtColor color;
public TShirt(TShirtSize size, TShirtColor color) {
this.size = size;
this.color = color;
}
public String toString() {
return size + "," + color;
}
public static void main(String[] args) {
TShirt t1 = new TShirt(TShirtSize.M, TShirtColor.RED);
System.out.println(t1); //Will print: M, RED;
TShirt t2 = new TShirt(TShirtSize.L, TShirtColor.WHITE);
System.out.println(t2); //Will print: L, WHITE;
}
}