Win a copy of Testing JavaScript Applications this week in the HTML Pages with CSS and JavaScript forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

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

 
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
 
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
 
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
 
I don't even know how to spell CIA. But this tiny ad does:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic