Static enumeration versus non-static enumeration

What is the difference between static and non-static enumeration in Java? Both use cases are the same.

Is it correct that all static ones are loaded into memory at startup, and non-static ones are loaded on demand? If so, which method is better? Saving some data always in memory or using server resources to load it every 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; } } 
+56
java enums static-members
Apr 17 '14 at 8:12
source share
4 answers

All enum effective static . If you have a nested enum, this is almost the same as a static class .

All classes are lazily loaded (enumerations or otherwise), however, when they are loaded, they are loaded immediately. that is, you cannot load multiple constants, but not others (except for the middle of the class initialization).

Java allows some modifiers to be hidden so that there is no need to declare them all the time. This means that adding a modifier does not have to do anything other than providing a longer way to write the same thing.

The default modifiers for

class / method / nested class - package local, not finite, non-static

enum and nested enum - local, final, and static package

interface field - public static final

interface - public abstract

nested class in interface - public static , not final

Note: while static is optional for enum , it is always static. However, final cannot be set to an enumeration, even if it always has the value final (technically you can have subclasses with overridden implementations for constants)

EDIT: The only place you need to use static with enum is with import static enumeration values. Thanks @ man910

+95
Apr 17 '14 at 8:19
source share

If you are talking about nested enums, they are implicitly static by default.

According to the Java language specification :

Nested enumeration types are implicitly static. It is permissible to explicitly declare a nested enumeration type as static.

+16
Apr 17 '14 at 8:18
source share

All enumerations are implicitly static, you just do not need to write the static . Similar to how all interface methods are implicitly public.

+10
Apr 17 '14 at 8:19
source share

Since enums are inherently static , it is not necessary and does not matter when using the static-keyword in enums .

If an enumeration is a member of a class, it is implicitly static.

Interfaces may contain member type declarations. An element type declaration in an interface is implicitly static and public.

Oracle Community Forum and Discussion

+3
Apr 17 '14 at 8:24
source share



All Articles