枚举作为实例变量 [英] Enum as instance variables

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

问题描述

如果您有枚举如

enum Coffee {
    BIG,
    SMALL
}

和一个具有枚举类型的实例变量的类:

and a class that has an instance variable like this of the enum:

public class MyClass {
    private Coffee coffee;

    // Constructor etc.
}

为什么可能在构造函数中说eg coffee.BIG
我不明白你可以使用引用吗?枚举作为实例变量初始化为除 null 之外的其他东西?第一章是SCJP书中的自检问题4。我试图缩短代码和问题。

Why is it possible in the constructor to say e.g. coffee.BIG? I don't understand that you can use the reference? Is enum as instance variables initialized to something other than null? It is the self test question #4 in the SCJP book in the first chapter. I tried to shorten the code and question.

推荐答案

enum Coffee {
    BIG,
    SMALL
}

BIG或SMALL是Coffee类的 public static final 字段,并且像所有静态字段一样,它们可以被类访问名字像

BIG or SMALL are public static final fields of Coffee class, and like all static fields they can be accessed by class name like

Coffee b1 = Coffee.BIG;

或通过与类相同类型的引用,如

or by reference of same type as class, like

Coffee s2 = b1.SMALL;
Coffee s3 = Coffee.BIG.SMALL; //BIG is reference of type Coffee so it is OK (but looks strange)

但是让我们记住我们应该避免通过引用访问静态成员。这会造成混乱,因为我们并没有真正访问实例的成员,而是的成员(所以例如没有多态)。

But lets remember that we should avoid accessing static members via references. This creates confusion since we are not really accessing members of instance but members of class (so for instance there is no polymorphic behaviour).

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

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