• Post Reply Bookmark Topic Watch Topic
  • New Topic

compile error: non-static reference (simple question)  RSS feed

 
Neill Laney
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code does not compile because testStatic is nons-static. Another thing that I've found is that member variables referenced from main must be static as well. Is this because testStatic is being called from the static method main? The code will compile if str and testStatic are declared static. Please help me understanding, TIA!
public class TestStatic {

String str;
public static void main(String[] args) {
testStatic();
str = null;
}
/**
* Method testStatic.
*/
void testStatic() {
}
}
 
Eric Fletcher
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
You can't have a non-static reference in a static context, i.e. in a static method(like the main method). This is because a static method or variable belongs to the class itself, not an instance of the class. A member variable only exists within the context of an instance of the class, so a non-static reference in a static context doesn't make sense and the compiler won't allow it.
To access a member variable or method from the main method, create and instance of the class inside the main method and call the method on that instance.

Or(like you have already discovered) you can make the methods and variables static themselves. That will make accessible from the main method as well.
HTH,
E
[ December 18, 2002: Message edited by: Eric Fletcher ]
[ December 18, 2002: Message edited by: Eric Fletcher ]
[ December 18, 2002: Message edited by: Eric Fletcher ]
 
Neill Laney
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks,
The part I was missing was to instantiate the class to get a handle to the instance variables and methods. Much cleaner than using the static modifier everywhere!
That's a big piece of the puzzle solved!
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!