本文介绍了public static void main()访问非静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它说非静态变量不能在静态方法中使用。但是public static void main呢。怎么样?

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

推荐答案

不,它没有。

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

但是

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

或者如果你实例化 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!
  }
}

此外

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

将起作用,因为 a 是一个局部变量,而不是实例变量。无论方法是否为 static ,方法局部变量在执行方法期间始终可以访问。

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.

这篇关于public static void main()访问非静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:37