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

non-static variable this cannot be referenced from a static context

 
Svend Rost
Ranch Hand
Posts: 904
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!
Im currently reading about modifiers for members and acording (or atleast that's what im understanding!) to K. Mughal you can access a non static member in a static method by using a reference of the object.
But, like I expected I get an error when I compile the following code.

Have I made an error? or can't I read english
btw. Is it (if so how?) possible to get access to a non instance var from within a static method.
Thanks in advance
/Svend Rost
 
shweta mathur
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Svend,
What Khalid Mughal wants to say, is that you cannot call a non-static member directly in a static method. But you can always use a reference object of this class to call the non-static method.
But "this" reference cannot be used, as static method is not associated with any object rather its associated only with the class. To call a non-static member you first have to create a new object and use the reference of this object to call the non-static method.
Like done in the following code -


Hope this helps !
Shweta
 
Dwipal Desai
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Static methods do not execute inside the instance of object of a class and are independent of that.
So when u say "this.i" in a static method, it will give a compilation error as "this" is not present for static methods.
If u want a static method to do some function on instance of your class, then u will have to pass it as an argument to the method.
For example,

public static void method(Modifier m)
{
int g = m.i;
}

Hope this helps
-Dwipal
 
Svend Rost
Ranch Hand
Posts: 904
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks both
all understood now
/Svend Rost
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic