aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes non-static variable this cannot be referenced from a static context Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "non-static variable this cannot be referenced from a static context" Watch "non-static variable this cannot be referenced from a static context" New topic
Author

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

Svend Rost
Ranch Hand

Joined: Oct 23, 2002
Posts: 904
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

Joined: Sep 23, 2002
Posts: 109
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


--Shweta<br />SCJP 1.4 <br />SCWCD
Dwipal Desai
Greenhorn

Joined: Dec 08, 2002
Posts: 2
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

Joined: Oct 23, 2002
Posts: 904
Thanks both
all understood now
/Svend Rost
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: non-static variable this cannot be referenced from a static context