• Post Reply Bookmark Topic Watch Topic
  • New Topic

enum problem  RSS feed

 
Sawan Mishra
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Code tags and formatting added - please see UseCodeTags for details]
if c were ref to any object then output would have been nullpointerException but its not.
My question is how c,the static field of test gets initialised??
c=null but c.RAINY n c.Sunny works f9. how??

my 2nd doubt:
why output is:
null
c c Sunny
Rainy

why output isn't
null
c Sunny
c Rainy

book says
All of an enum’s values are initialized at the same time

then if I don't access enum's values why it doesn't print c c??
also please tell me some source(website or book) to study thoroughly these enums..
thanks in advance


thanks in advance
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static values and methods - and enum values can be considered static - should be accessed via their class name. But Java does allow (and this was arguably a mistake) them to be accessed via a reference. The reference type is then used. you should never actually do this because it leads to confusion (as in this case!), but the compiler allows it.

So this:
is really equivalent to

So the static variable c never actually gets initialised, as you'll see if you print out the value again at the end.
 
Campbell Ritchie
Marshal
Posts: 56553
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
…and there is the confusing feature that the compiler “knows” the type of c even if it is null. So it can find Weather as its class and find Weather.SUNNY.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:…and there is the confusing feature that the compiler “knows” the type of c even if it is null. So it can find Weather as its class and find Weather.SUNNY.

You know what? I'd forgotten all about that. Have a cow, man.

Winston
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!