Trying to create a custom (user-defined) data type, who's value can only possibly be one of a few options, like different states. Something like:
trafficLight = [ "red" | "amber" | "green" ];
or
coin = [0.01 | 0.02 | 0.05 | 0.1 | 0.2 | 0.5 | 1 | 2];
In these examples I guess trafficLight
is just a String
with limited options, and similarly, coin
and int
.
I think I need to class for these new data types, but how do I restrict the possible values assigned to variables of these custom data types?
You could use an enum
public enum TrafficLight {
RED, AMBER, GREEN;
}
as per https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
As enum is neither String
or int
you will have to map it to your desired type and this can be done in few different ways eg by calling existing String toString()
or defining custom int getValue()
method.
How about using enum. Below is an example of how it could be used. By using enum as the parameter to your methods, you restrict the values to only what the enum allows.
public class MyNewType {
public void someMethod(TrafficLight tl, Coin coin) {
//do something
}
public static enum TrafficLight {
red, amber, green;
}
public static enum Coin {
oneCent(.01f), twoCent(.02f), fiveCent(.05f), tenCent(.1f), fiftyCent(.5f), oneDollar(1f), twoDollar(2f);
private Coin(float amount) {
this.amount = amount;
}
float amount;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.