Java – why is enum considered safer than constants?

In our example, we can choose to define an enumeration type that will limit the possible specified values (i.e. improved type security):

public class OfficePrinter {

public enum PrinterState { Ready,OutOfToner,Offline };
public static final PrinterState STATE = PrinterState.Ready;
}

static final char MY_A_CONST = 'a';

Solution

Imagine these two method signatures:

void rawF(char someFlag);

void enumF(MyFlags someFlag);

The latter is more restrictive because only valid values of myflags are allowed In the former case, any character can be passed - even if only the value defined in "constant" is used

The code of happiness

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>