Java 中的枚举.好处? [英] Enum in Java. Advantages?

查看:21
本文介绍了Java 中的枚举.好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中使枚举类似于类,而不是像 C/C++ 中那样只是常量的集合有哪些优点?

What are some advantages of making enum in Java similar to a class, rather than just a collection of constants as in C/C++?

推荐答案

您可以免费在编译时检查有效值.使用

You get free compile time checking of valid values. Using

public static int OPTION_ONE = 0;
public static int OPTION_TWO = 1;

不保证

void selectOption(int option) {
...
}

只接受 0 或 1 作为参数值.使用枚举,这是有保证的.此外,这会导致更多的自记录代码,因为您可以使用代码完成来查看所有枚举值.

will only accept 0 or 1 as a parameter value. Using an enum, that is guaranteed. Moreover, this leads to more self documenting code, because you can use code completion to see all enum values.

这篇关于Java 中的枚举.好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆