• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 904
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks both
all understood now
/Svend Rost
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic