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 static main function Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "static main function" Watch "static main function" New topic

static main function

Timothy Leong
Ranch Hand

Joined: May 25, 2005
Posts: 55
Dear all,

I have d following program in this format. I have problem creating Person object in the method1(); its stated "Non static variable cannot be refereced..". btw, under what circumstances I can use public void method1() instad of public static void method1() instead??

public class testing
Person a,b;
public static void main(String args[])

public static method1()
a = new Person();

thank u for ur reply
Shyam Prasad Murarka
Ranch Hand

Joined: May 02, 2005
Posts: 209
Dear Readers,
If you explicitly create an object of "testing' class then you can invoke method1() in the following way:

And by the way by convention we use Capital letters for a class name. And also please use UBB code tags to make your post more readable.

With Best Regards,
Shyam Prasad Murarka
Philip Heller
Ranch Hand

Joined: Oct 24, 2000
Posts: 119
Non-static variables are associated with instances of a class. So in your program, every instance of testing has its own a and b. In a non-static method, the statement

is an abbreviation for
In other words, the statement sets the value of x of the current object.

In static code, you aren't dealing with individual objects/instances. There is no current object. So when your method1 uses the variable , the compiler doesn't know which "a" you meant.

Static methods may not read/write non-static variables, and may not call non-static methods, unless they explicitly specify which object owns the var or the method. SO the following would compile ok:

Hope this helps.

Consultant to SCJP team.<br />Co-designer of SCJD exam.<br />Co-author of "Complete Java 2 Certification Study Guide".<br />Author of "Ground-Up Java".
I agree. Here's the link:
subject: static main function
It's not a secret anymore!