• Post Reply Bookmark Topic Watch Topic
  • New Topic

enums as static varialbes in a class  RSS feed

 
Pavan Upadhya
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a class which as one of the static member of type enum. Below is the code


The output of the code is WINTER. But the question I have is, by default all non-initialized static members will be initialized to null. So I was expecting a NULL Pointer Exception while printing s.WINTER. Could some one explain why s is not initialized to null in this case.

Thanks,
Pavan
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


If you print s it will give you null, so it is initialized to null.

But if you print


It will give you WINTER, as WINTER is static final object in the enum SEASON, compiler can detect it, so compiler replace that call with SEASON.WINTER.

If you run below code, you will get the same behavior.

 
Pavan Upadhya
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Punit, Now I recollect all enums are public, final and static.
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No no recollect all enum constants are public static final.
 
Pavan Upadhya
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oops! sorry for the typo. Actually I meant enum constants.
 
pete stein
Bartender
Posts: 1561
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You shouldn't be doing this:

as you're obtaining a static member from an instance (null or not). Better and more honest is this:

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!