Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Enum program (Small problem)  RSS feed

 
Manish Dubey J
Greenhorn
Posts: 9
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After running following code-



I got output as- c c 1 1
But I expected it c 1 c 1
Where am I wrong?
Help!
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You put System.out.print("c "); in the Weather constructor. Enums are constants at runtime, they are built before they are used, when the enum is first loaded and statically initialized. So the two Weather enums (RAINY and Sunny) are constructed before you can access either of the two enum values. So you get 'c' printed twice, before either count is printed.
 
Manish Dubey J
Greenhorn
Posts: 9
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A tiny edit in my last post- I expected c 1 c 2.

But before that, consider this code-

Now also "c" is printed two times ie c c 1, though I have only used "w.RAINY.count. Does that mean the constructor will run that number of time equal to enum constants, no matter what and how we use?

Please comment on my first ques also. (In explanation in this book I am using, its written, an enum’s
variables are treated as if they were instance variables, not static variables)
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Manish Dubey J wrote:Now also "c" is printed two times ie c c 1, though I have only used "w.RAINY.count. Does that mean the constructor will run that number of time equal to enum constants, no matter what and how we use?
Yes, like I said before, enums are created when the enum class is first statically initialized. This is before you access any of them, and so it doesn't matter which or how many of the enums are accessed, all of them are created when the enum class is initially referenced.

A tiny edit in my last post- I expected c 1 c 2.
...
Please comment on my first ques also. (In explanation in this book I am using, its written, an enum’s
variables are treated as if they were instance variables, not static variables)

Yes. That is correct, the variable 'count' is an instance variable. And since each enum constant (RAINY and Sunny) is a different instance of the containing enum, they each have their own variable 'count' and they both get incremented independently.
 
Manish Dubey J
Greenhorn
Posts: 9
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understood this concept.
Thank you Steve!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!