Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static main function

 
Timothy Leong
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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[])
{
method1();
}

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

thank u for ur reply
 
Shyam Prasad Murarka
Ranch Hand
Posts: 209
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Philip Heller
author
Ranch Hand
Posts: 119
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic