I'm trying to figure out what is the best solution for my problem.
I have an object where the status may be one of three possibilities but it can change during run time. I have three status flags that the object can be.
I have no experience with ENUM
and trying to figure out if this is the best way.
I want to be able to set a specific flag to true
or false
and then be able to set another one. I need to be able to get the status of each flag as well for when I iterate through a list of these objects within a array list.
class Patient
{
//REST OF the object
public enum Status
{
INPATIENT(false),
OUTPATIENT(false),
EMERGENCY(false);
private final boolean isStatus;
Status(boolean isStatus)
{
this.isStatus = isStatus;
}
public boolean isStatus()
{
return this.isStatus;
}
}
}
Use the Boolean to Enum Refactoring to convert two-state structures (method return types or method parameter types) into multiple-state structures. Enums have the following advantages. Structure states describe themselves, which improves code readability.
An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).
The Java compiler internally adds the valueOf() method when it creates an enum. The valueOf() method returns the value of given constant enum.
Inside randomDirection(), we call the method nextInt() with an integer argument. The nextInt() method returns a random number to access the directions array; therefore, we need to make sure the integer is not out of the bounds of the array by passing a bound argument to nextInt().
That's not really how an enum
works. You wouldn't include the boolean
flag, but instead do this:
public enum Status {
INPATIENT,
OUTPATIENT,
EMERGENCY;
}
public class Patient {
private Status status;
public void setStatus(final Status status) {
this.status = status;
}
}
public class SomeService {
public void someMethod(final Patient patient) {
patient.setStatus(Status.INPATIENT);
patient.setStatus(Status.OUTPATIENT);
patient.setStatus(Status.EMERGENCY);
}
}
A variable typed as an enum
can hold any one value of that enum
(or null
). If you want to change status, change which value of the enum the variable refers to. (Enum
s are different from class
es, since they are not instantiated with the new
keyword, but rather just referenced directly, as in the above code.)
public enum StatusFlag { OUTPATEINT, INPATIENT, EMERGENCY}
public class Patient {
private StatusFlag status;
// Here goes more code
}
This will ensure that it would be impossible to assign any other values to status
field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With