java - 看到 enum 后对 Java 中的类型声明感到困惑

标签 java enums

作为 Java 初学者,我接触到了枚举,这让我对类型声明感到非常困惑。我想把我所知道的分享出来,以便大家可以按照我的思路发现问题。

我了解到有两种数据类型,原始数据类型和对象数据类型。声明变量时,首先写入变量的数据类型,然后写入标识符

当我声明一个数据类型 int 变量时,我脑子里有以下想法:

int a = 1; int as datatype references to the primitive integer datatype.

当我声明一个数据类型 Integer 变量时,我脑子里有以下想法:

Integer b =  1;  Integer as datatype references to the object datatype (that in this case is an instance of the class integer)

当我声明一个枚举变量时,我脑子里有以下想法:

enum C {EXAMPLE1, EXAMPLE2}; No clue what enum references to.. Is it an object datatype and an instance of class enum? If so, where is the capital letter E in enum.

问题就从这里开始了。我了解到枚举不是原始数据类型,因此唯一的可能性是它是一个对象。但我还了解到,将类的对象声明为数据类型意味着标识符应以大写字母开头,如整数、 boolean 值等。但是,我可以声明不带大写字母的枚举。这是否意味着它不是一个对象?或者枚举器只是像 class 这样的关键字,而不是像我想象的那样的变量数据类型。

如果 enum 不是变量数据类型,而是像 class 这样的关键字,那么我想知道以下心态是否正确:

enum Test {EXAMPLE1, EXAMPLE2}
Test e = Test.EXAMPLE; Does Test reference to the object datatype? (That 
in this case is an instance of the enumerator Test) 

如果 Test 是枚举器 Test 的实例,这怎么可能?我只认为可以从类创建对象,但我也读过一些有关枚举器中的构造函数的内容。

我已经寻找这个问题的答案几个小时了,但没有成功。我希望我现在还没有搞乱你的头脑。但我真心希望有人能够理解这一点并真正帮助我。

最佳答案

I can however declare an enum without a capital letter. Does this mean it is not an object?

没有。

Or is an enumerator just a keyword like class and not a variable datatype like I assumed it to be.

enumclass 一样,是一个关键字 - 请参阅 JLS section 8.9 .

An enum declaration specifies a new enum type, a special kind of class type.

枚举常量是枚举类型的实例,枚举类型又扩展了Enum父类(super class)。

enum Test {EXAMPLE1, EXAMPLE2}

所以这里Test定义了一个枚举类型。 EXAMPLE1 和EXAMPLE2 是枚举常量,它们是Test 枚举类型的实例。运行时无法创建其他实例,但您可以创建对这些实例的其他引用。

Test e = Test.EXAMPLE

所以这里,局部变量e指向枚举常量;可以这么说,eTest.EXAMPLE 在内存中具有相同的地址。

Test.class 是一个有意义的构造 - 它使您可以访问由枚举声明定义的类实例。 Test.EXAMPLE.class 没有意义,e.class 也没有意义,因为它们是实例。 Test.EXAMPLE.getClass()e.getClass()

它非常类似于java.lang.Boolean

Boolean b = Boolean.TRUE

但不完全

Boolean b = new Boolean(true); // OK
Test    t = new Test(); // NOT ALLOWED

关于java - 看到 enum 后对 Java 中的类型声明感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52231460/

相关文章:

java - Tika、Maven、依赖项...为什么 Tika 使用 EmptyParser?

c# - LINQ 查询中奇怪的扩展方法行为

ruby-on-rails - 将 postgres ENUM 与 Rails 结合使用会产生 `PG::DatatypeMismatch`

java - 使用java嵌套#if宏处理

java - Selenium 网格和 azure

java - 未调用 Spring 安全自定义 LogoutHandler

Java 对象 : value for comparison in if statement, 运算符重载

ios - 快速替换旧式枚举

mysql - 如何从 mysql 中的枚举中删除值?

iphone - iOS 6.1 和 Xcode 4.6,枚举警告 UIView 动画曲线 EaseOut