public static void main () access non static varia

2019-03-09 12:21发布

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

6条回答
迷人小祖宗
2楼-- · 2019-03-09 12:52

**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

查看更多
Deceive 欺骗
3楼-- · 2019-03-09 12:58
public class XYZ
{
   int i=0;
   public static void increament()
       {
       i++;   
       }
}
public class M
{
    public static void main(String[] args)
    {
    XYZ o1=new XYZ();
    XYZ o2=new XYZ();
    o1.increament(); 
    XYZ.increament(); //system wont be able to know i belongs to which object 
                  //as its increament method(static method)can be called using   class name system 
                  //will be confused changes belongs to which object.
    }
}
查看更多
啃猪蹄的小仙女
4楼-- · 2019-03-09 12:59

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#...)

查看更多
Anthone
5楼-- · 2019-03-09 13:01

You can create non-static references in static methods like :

static void method() {
   A a = new A();
}

Same thing we do in case of public static void main(String[] args) method

查看更多
放我归山
6楼-- · 2019-03-09 13:06

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.

查看更多
虎瘦雄心在
7楼-- · 2019-03-09 13:13

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).

查看更多
登录 后发表回答