File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Cannot reference non-static error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Cannot reference non-static error" Watch "Cannot reference non-static error" New topic

Cannot reference non-static error

Tempora Telora
Ranch Hand

Joined: Jun 20, 2005
Posts: 83
Hello all,

I feel lost right now.

I have trying to reference a method from main ... test()

i have test has public void test() { System.out.println("hello"); }

but when I do that it comes back with non-static error. Why do I have to use a static method?

Why do I have to use the static variables outside of main?

I know i have done this before where outside of main I have private int counter = 0;

then in main I do counter++ but it keeps barfing on me. Any ideas?
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
The main method is a static method. It can directly access only static members of the class.
[ May 03, 2007: Message edited by: Keith Lynn ]
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46405
A very common problem, partially caused because so many sources, even the Java Tutorial, put too much coding into the main method. That is convenient because they can get more code into less space, but it isn't good object-oriented programming. The main method should have very little in it; if you get down to one statement, so much the better.
If your test method is in a class called HelloClass, try this:-You are actually creating an object there.
I agree. Here's the link:
subject: Cannot reference non-static error
It's not a secret anymore!