Restricting arguments to certain defined constants
Consider the following code
public class ColorScheme {
public static final int DARK_BLACK = 0,
WHITE = 1;
private int Scheme;
public ColorScheme() {
this.Scheme = DARK_BLACK;
}
public ColorScheme(int SchemeType) {
this.Scheme = SchemeType;
}
}
I want the argument to the constructor ColorScheme(int SchemeType)
to be restricted to one of the static final int
- DARK_BLACK
or WHITE
or other constant I may define.
For Ex: When someone instantiates the ColorScheme
class, he can use
ColorScheme CS = new ColorScheme(DARK_BLACK);
开发者_StackOverflow中文版while
ColorScheme CS = new ColorScheme(5); //or any other non-defined constant
should return an error.
You're looking for Java enums.
Enum is the way to go:
public class ColorScheme {
public enum Color {DARK_BLACK,
WHITE}
private Color Scheme;
public ColorScheme() {
this.Scheme = Color.DARK_BLACK;
}
public ColorScheme(Color SchemeType) {
this.Scheme = SchemeType;
}
}
maybe you could consider to use Enum http://download.oracle.com/javase/tutorial/java/javaOO/enum.html
As Mat and Kent have already pointed out: enum's the way to go.
Enums are quite powerful, since they offer many concepts you have with classes, e.g. methods and constructors. The corresponding chapters in Effective Java from Josh Bloch, the author of enums, is definitely worth a read, since they describe the many advantages, the disadvantages, as well as several use cases, e.g. EnumMaps and EnumSets.
精彩评论