静态枚举与非静态枚举 [英] Static enum vs. Non-static enum

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

问题描述

Java中静态和非静态枚举有什么区别?这两个用法都是一样的。

What's the difference between static and non-static enum in Java? Both usages are same.

正确的是, 所有静态的都在启动时加载到内存上,而非静态的则根据需要加载
如果是,那么哪种方法更好?保持一些数据总是在内存中或使用服务器资源来加载它们每次?

Is it correct that all static ones are loaded on memory on startup, and non-static ones are loaded on demand? If yes, then which method is better? Keeping some data always in memory or using server resources to load them each time?

public class Test {

    public enum Enum1 {
        A, B
    }

    public static enum Enum2 {
        C, D
    }

    public static void main(String[] args) {
        Enum1 a = Enum1.A;
        Enum1 b = Enum1.B;

        Enum2 c = Enum2.C;
        Enum2 d = Enum2.D;
    }
}


推荐答案

枚举有效地 static 。如果你有一个嵌套的枚举,它与一个静态类是一样的。

All enums are effectively static. If you have a nested enum, it is much the same as a static class.

所有类都被延迟加载(枚举或其他),但是当它们被加载时,它们一起被加载。即,您不能加载几个常量,而不是其他常量(除了初始化类之外)

All classes are lazily loaded (enums or otherwise) however when they are loaded they are loaded all at once. i.e. you can't have a few constants loaded but not others (except in the middle of class initialization)

Java允许某些修饰符为隐式,以避免必须声明它们每时每刻。这意味着添加修饰符并不一定要提供更长的写作方式。

Java allows certain modifiers to be implicit to avoid having to declare them all the time. This means that adding a modifier doesn't necessarily do anything other than provide a longer way of writing the same thing.

class field / method / nested class - package local,non-final,non-static

class field/method/nested class - package local, non-final, non-static

枚举和嵌套枚举 - 包本地,最终和静态

enum and nested enum - package local, final and static

接口字段 - public static final

界面方法 - public abstract

界面中的嵌套类 - public static 非最终

nested class in an interface - public static, non-final

注意:静态对于是可选的枚举它总是静态的。但是, final 不能设置为枚举,即使它始终是名义上的 final (从技术上讲,您可以覆盖子类

Note: while static is optional for an enum it is always static. However, final cannot be set for an enum even though it is always notionally final (Technically you can have subclasses with overridden implementations for constants)

编辑:唯一需要使用 static 枚举的地方与枚举值的 import static 。谢谢@ man910

The only place you need to use static with enum is with import static of an enum's value. Thank you @man910

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

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