Java枚举常量 [英] Java enums over Constants

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

问题描述


可能重复:

了解Java中的枚举

我们为什么要使用枚举而不是Java常量?

Why should we use enums rather Java constants?

我已经读过Java枚举提供了类型安全性。有人可以详细说明吗?或者使用枚举超过常量还有其他优点吗?

I have read that Java enums gives type safety. Can somebody please elaborate it? Or there is any other advantage of using enum over constants?

推荐答案

引用 http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}

当你有这个方法时:

public EnumTest(Day day) {
    this.day = day;
}

你知道这个论点总是一天。

you know that the argument is always going to be a day.

与此相比:

const int MONDAY = 1;
const int TUESDAY = 2;

const int CAT = 100;
const int DOG = 101;

您可以将任何传递给此方法:

you could pass anything to this method:

public EnumTest(int day) {
    this.day = day;
}

使用枚举 (或任何类型,如类或接口)为您提供类型安全:类型系统确保您只能获得所需的类型。第二个例子在这方面不是类型安全的,因为你的方法可以将任何int作为参数,并且你不确定int值的含义。

Using an enum (or any type, such as a class or interface) gives you type safety: the type system makes sure you can only get the kind of type you want. The second example is not type safe in that regard, because your method could get any int as an argument, and you don't know for sure what the int value means.

使用枚举是调用代码和被调用的代码之间的契约,给定的值是给定类型。

Using the enum is a contract between the calling code and the code being called that a given value is of a given type.

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

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