Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

constant specific class body in an enum

 
Kendall Ponder
Ranch Hand
Posts: 205
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wrote the following code to test my understanding of enums. It isn't intended to accomplish anything other than to demonstrate overriding a method using a constant specific class body.


When I compile the code I get a "non-static variable value can't be accessed in static context" error where I try to return 2*value in line 3 of the code. There is no problem with return value on line 13 of the code. If I replace 2*value with 33 it works fine. If I replace value with this.value it tells me value is private. Is there a way to access value in the overriding method? Thanks!
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Kendall,

Kendall Ponder wrote:Is there a way to access value in the overriding method?

What about using the super keyword to invoke the returnValue method?


Or you could add an extra getValue method with at least default access to use in your constant specific class body, like this:


Hope it helps!
Kind regards,
Roel
 
Kendall Ponder
Ranch Hand
Posts: 205
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roel,
Thanks for the input. Sorry it took so long to respond. Does the "constant specific class body in the enum" act
like a subclass of the enum? Is that why the method returnValue() in the "constant specific class body
cannot directly access the variable value but the method returnValue() in the enum can? Thanks again.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kendall Ponder wrote:Does the "constant specific class body in the enum" act
like a subclass of the enum? Is that why the method returnValue() in the "constant specific class body
cannot directly access the variable value but the method returnValue() in the enum can?

If you compile enum Temp, you'll get 2 class files: Temp.class and Temp$1.class, so that screams subclass If you decompile the Temp$1.class file (using JAD for example) you'll get this code:


That explains the compiler error: value is a private instance variable, so it can't be accessed from this subclass. So using a public (or protected or default) method will make your enum compile successfully.

Hope it helps!
Kind regards,
Roel
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic