public static void main()访问非静态变量

use*_*671 13 java variables static-methods program-entry-point void

它表示非静态变量不能用于静态方法.但是public static void main.如何?

Kep*_*pil 26

不,它没有.

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

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

或者如果你实例化 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!
  }
}
Run Code Online (Sandbox Code Playgroud)

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

将工作,因为a这里是一个局部变量,而不是实例变量.无论方法是否存在,方法局部变量总是在方法执行期间可达static.


aio*_*obe 10

是的,main方法可以访问非静态变量,但只能通过实际实例间接访问.

例:

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

class Example {
    public int variable;
}
Run Code Online (Sandbox Code Playgroud)

当人们说"非静态变量不能在静态方法中使用"时,人们的意思是不能直接访问同一类的非静态成员(例如,如Keppils的回答所示).

相关问题:


更新:

在谈论非静态变量时,隐含地意味着成员变量.(因为无论如何局部变量都不可能有静态修饰符.)

在代码中

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

你正在声明一个局部变量(即使它没有静态修饰符,通常也不会被称为非静态变量).