• Post Reply Bookmark Topic Watch Topic
  • New Topic

static variables  RSS feed

 
rizwana mujawar
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have not started with static variables and method.. But i want to know what this error is trying to tell me.... Its throwing an error "non static method cannot be referenced from static context".. Adding static to my goldCoin() will resolve my problem but i dint understand the meaning of my error.... Hey Guys is there any site which helps me to do chapter wise(Kathy Sierra Book) preparation for SCJP.... After reading my one chapter i want to give mocks on that chapter itself.... Thanks for all your valuable replies in advance
 
Joe Vahabzadeh
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hobbit is a class.

goldCoin is a method for the Hobbit class.

However, in your code, you're trying to call goldCoin directly without having a Hobbit. In other words, you're trying to call goldCoin as if it were a static method, which it is not.

Thus, you would actually need to change your System.out.println statement to be two lines, something like this:


The reason your original code worked when you changed goldCoin to static is because a static method is one that is available without the need for an instance of the class it's contained in. So in this case, once you made goldCoin static, you no longer needed an instance of a Hobbit object to call it.

I hope this helps...
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem with that method is that it doesn’t really do anything. All it does is add to 7 and return the value. You called the thread static variables, but you haven’t got any static variables. You haven’t got any fields at all in the Hobbit class. You need to revise fields, and work out how Hobbit bilbo can have 8 coins and Hobbit frodo can have 9 coins. Look up basic UML and draw a class diagram for the Hobbit class. Remember: the coins field should be a private instance field.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!