• Post Reply Bookmark Topic Watch Topic
  • New Topic

Exchange information between static methods and non-static methods  RSS feed

 
Evert DeBoer
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I spent a large part of the day reading about the difference between static methods and non-static methods.

However, what I don't understand is how to exchange information between these two types of methods.

For example, if I have a static method and I want to get a value from a non-static method, I get an error message "non-static field cannot be referenced from a static context" if I call NSM.variable, where NSM is a non-static method and variable a (non-static) variable in it. The other way around is similar.

How can I get information from a non-static method using a static method?
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A non-static method can only be accessed via an object reference, so you'll need an object reference if you want to call it from a static context. Note that when you see code that calls a non-static method without an explicit object reference, the implicit object reference being used is "this", i.e. the current object.  That's why these lines 4 and 5 below are equivalent:

this only has meaning in a non-static context; there is no "this" in a static context in Java
 
s ravi chandran
Ranch Hand
Posts: 579
6
Java jQuery
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This might not be a solution, but a pointer to what you are trying.

Here is a sample code passing value to non static context from static context.

Point to note is I am calling static method from instance variable. But this should strictly be avoided unless you make a conscious decision to use it as calling static method from non static context will never have any instance state. They will be visible to all instances of the class.

Calling non static method/ variable in static method is not permitted.
 
Stephan van Hulst
Saloon Keeper
Posts: 7991
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
NSM.variable is illegal syntax, if NSM is a method name.

Static members of a class can be accessed via the class name. Non-static members can only be accessed through an object reference. You can get a reference to the current object using the this keyword. When you're inside a static method, there is no current object, so when you want to access a non-static member, you must specify which object you want to access the member of:
 
Evert DeBoer
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks all! I've got it working.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!