Skip to content

Instantly share code, notes, and snippets.

@rklemme
Created March 29, 2011 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rklemme/892503 to your computer and use it in GitHub Desktop.
Save rklemme/892503 to your computer and use it in GitHub Desktop.
Example demonstrating two approaches to implement boolean properties for enums
public final class PropVsMeth {
/** We use boolean properties. */
public enum Prop {
A(true, true), B(true, false), C(false, true);
private final boolean a;
private final boolean b;
Prop(boolean a, boolean b) {
this.a = a;
this.b = b;
}
public boolean isA() {
return a;
}
public boolean isB() {
return b;
}
}
/** We use custom methods. */
public enum Meth {
A, B {
@Override
public boolean isB() {
return false;
}
},
C {
@Override
public boolean isA() {
return false;
}
};
public boolean isA() {
return true;
}
public boolean isB() {
return true;
}
}
public static void main(String[] args) {
System.out.println(Prop.class.getName());
for (final Prop p : Prop.values()) {
System.out.println(p + " a=" + p.isA() + " b=" + p.isB());
}
System.out.println(Meth.class.getName());
for (final Meth p : Meth.values()) {
System.out.println(p + " a=" + p.isA() + " b=" + p.isB());
}
}
}
package en;
/**
* Valve state.
*/
public enum Valve {
CLOSED(false, false), HALF_OPEN(true, false), FULL_OPEN(true, true);
private final boolean open;
private final boolean unlimited;
private Valve(final boolean open, final boolean unlimited) {
this.open = open;
this.unlimited = unlimited;
}
/**
* Check whether anything can pass.
*
* @return if we allow at least a dribble.
*/
public boolean isOpen() {
return open;
}
/**
* Check whether any traffic restrictions apply.
*
* @return <code>true</code> if no restrictions apply.
*/
public boolean isUnlimited() {
return unlimited;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment