This question already has an answer here:
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;
}
}
As
enums
areinherently static
, there is no need and makes no difference when usingstatic-keyword
inenums
.If an enum is a member of a class, it is implicitly static.
Interfaces may contain member type declarations. A member type declaration in an interface is implicitly static and public.
Oracle Community Forum and Discussion On This
All
enum
s are effectivelystatic
. If you have a nested enum, it is much the same as astatic 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 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.
Default modifiers for
class field/method/nested class - package local, non-final, non-static
enum and nested enum - package local, final and static
interface field -
public static final
interface method -
public abstract
nested class in an interface -
public static
, non-finalNote: while
static
is optional for anenum
it is always static. However,final
cannot be set for an enum even though it is always notionallyfinal
(Technically you can have subclasses with overridden implementations for constants)EDIT: The only place you need to use
static
withenum
is withimport static
of an enum's value. Thank you @man910If you're talking about nested enums, they are implicitly
static
by default.According to the Java Language Specification:
All Enums are implicitly static, its just you don't need to write the
static
keyword. Similarly to the way all interface methods are implicitly public.