public static void main () access non static variable

49,084

Solution 1

No, it doesn't.

public class A {
  int a = 2;
  public static void main(String[] args) {
    System.out.println(a); // won't compile!!
  }
}

but

public class A {
  static int a = 2;
  public static void main(String[] args) {
    System.out.println(a); // this works!
  }
}

or if you instantiate A

public class A {
  int a = 2;
  public static void main(String[] args) {
    A myA = new A();
    System.out.println(myA.a); // this works too!
  }
}

Also

public class A {
  public static void main(String[] args) {
    int a = 2;
    System.out.println(a); // this works too!
  }
}

will work, since a is a local variable here, and not an instance variable. A method local variable is always reachable during the execution of the method, regardless of if the method is static or not.

Solution 2

Yes, the main method may access non-static variables, but only indirectly through actual instances.

Example:

public class Main {
    public static void main(String[] args) {
        Example ex = new Example();
        ex.variable = 5;
    }
}

class Example {
    public int variable;
}

What people mean when they say "non-static variables cannot be used in a static method" is that non-static members of the same class can't be directly accessed (as shown in Keppils answer for instance).

Related question:


Update:

When talking about non-static variables one implicitly means member variables. (Since local variables can't possible have a static modifier anyway.)

In the code

public class A {
    public static void main(String[] args) {
        int a = 2;
        System.out.println(a); // this works!
    }
}

you're declaring a local variable (which typically is not referred to as non-static even though it doesn't have a static modifier).

Solution 3

**Here you can see table that clear the access of static and non-static data members in static and non-static methods. **static non-static table

Solution 4

The main method does not have access to non-static members either.

final public class Demo
{
   private String instanceVariable;
   private static String staticVariable;

   public String instanceMethod()
   {
      return "instance";
   }

   public static String staticMethod()
   {
      return "static";
   }

   public static void main(String[] args)
   {
      System.out.println(staticVariable); // ok
      System.out.println(Demo.staticMethod()); // ok

      System.out.println(new Demo().instanceMethod()); // ok
      System.out.println(new Demo().instanceVariable); // ok

      System.out.println(Demo.instanceMethod()); // wrong
      System.out.println(instanceVariable);         // wrong 
   }
}

This is because by default when you call a method or variable it is really accessing the this.method() or this.variable. But in the main() method or any other static method(), no "this" objects has yet been created.

In this sense, the static method is not a part of the object instance of the class that contains it. This is the idea behind utility classes.

To call any non-static method or variable in a static context, you need to first construct the object with a constructor or a factory like your would anywhere outside of the class.


More depth:

Basically it's a flaw in the design of Java IMO which allows static members (methods and fields) to be referenced as if they were instance members. This can be very confusing in code like this:

Thread newThread = new Thread(runnable);
newThread.start();
newThread.sleep(1000);

That looks like it's sending the new thread to sleep, but it actually compiles down into code like this:

Thread newThread = new Thread(runnable);
newThread.start();
Thread.sleep(1000);

because sleep is a static method which only ever makes the current thread sleep.

Indeed, the variable isn't even checked for non-nullity (any more; it used to be, I believe):

Thread t = null;
t.sleep(1000);

Some IDEs can be configured to issue a warning or error for code like this - you shouldn't do it, as it hurts readability. (This is one of the flaws which was corrected by C#...)

Share:
49,084
user1526671
Author by

user1526671

Updated on August 01, 2020

Comments

  • user1526671
    user1526671 almost 4 years

    Its said that non-static variables cannot be used in a static method.But public static void main does.How is that?

  • user1526671
    user1526671 almost 12 years
    public class A { public static void main(String[] args) { int a = 2; System.out.println(a); // this works! } } my question is how does tis works
  • user1526671
    user1526671 almost 12 years
    'public class A { public static void main(String[] args) { int a = 2; System.out.println(a); // this works! } }' this doesn't use any instances
  • Bbvarghe
    Bbvarghe almost 11 years
    so where are static methods and variable contained if not in the class they are defined in?
  • Lion
    Lion almost 11 years
  • Bbvarghe
    Bbvarghe almost 11 years
    so the only way main could access the instanceMethod and instanceVariable is if it made an object of the Demo class?
  • Lion
    Lion almost 11 years
    if instanceMethod and instanceVariable were instance method and instance variable respectively, then they could only be accessed from a static method by dereferencing them by the object of their respective class.