Example demonstrating two approaches to implement boolean properties for enums
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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