Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is the default value of an enum?

 
Pujan Kafle
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have been baffled by K&B Chapter I question 4. about enums.



For some reason, when I first answered this question, I selected the answer A (i.e. woof burble)
But after studying in preparation of OCPJP, when I revisited this question, I thought what would be the default value of an enum?
In TestEnum, Animals has only been declared but not assigned to any value. So, I thought a would be null.
Can anyone please give a nice clarification regarding the default value of an enum?

I would really appreciate it.

Thanks.
 
Pujan Kafle
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After thinking for a while, I'll try to give it a shot.

Is it because, Animals has been declared as static and behind the scenes calling a.DOG.sound translates to Animals.DOG.sound?

Maybe my mind has become saturated and I have been looking everything with a captious mind and not been able to figure out subtle details.

I would appreciate your suggestions.
 
Ankit Garg
Sheriff
Posts: 9510
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pujan Kafle wrote:Is it because, Animals has been declared as static and behind the scenes calling a.DOG.sound translates to Animals.DOG.sound?

Yes you are right that a.DOG.sound would be converted to Animals.DOG.sound but not because a is declared static. Its because enum variables are all static. Basically an enum is translated into a normal Java class which extends java.lang.Enum. So your enum after compilation would become something like this
And as you might know, if we access any static members of a class using a reference variable of the class (in your case its a), then the compiler replaces the name of the reference variable with the class name (in your case a would be replaced by Animala)...
 
Pujan Kafle
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much Ankit for your clarification. This clears all the confusion.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic