• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

enums as static varialbes in a class  RSS feed

 
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
 
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.
 
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:

 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!