• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

static main function

 
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 209
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
author
Posts: 119
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic