通过Java中的main方法访问非静态成员

Bha*_*esh 11 java

作为面向对象范例的规则,静态方法只能访问静态变量和静态方法.如果是这样的话,就会出现一个明显的问题,即Java中的main()方法如何能够访问非静态成员(变量或方法),即使它是特定的public static void ... !!!

tjg*_*184 25

main方法也无法访问非静态成员.

public class Snippet
{
   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(Snippet.staticMethod()); // ok

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

      System.out.println(Snippet.instanceMethod()); // wrong
      System.out.println(instanceVariable);         // wrong 
   }
}
Run Code Online (Sandbox Code Playgroud)


Oli*_*rth 6

通过创建该类的对象.

public class Test {
    int x;

    public static void main(String[] args) {
        Test t = new Test();
        t.x = 5;
    }
}
Run Code Online (Sandbox Code Playgroud)


Des*_*hou 5

main() 方法无法访问非静态变量和方法,当您尝试这样做时,您将得到 \xe2\x80\x9cnon-static method can be referenced from a static context\xe2\x80\x9d 。

\n\n

这是因为默认情况下,当您调用/访问方法或变量时,它实际上是在访问 this.method() 或 this.variable。但在 main() 方法或任何其他静态方法() 中,尚未创建“this”对象。

\n\n

从这个意义上说,静态方法不是包含它的类的对象实例的一部分。这就是实用程序类背后的想法。

\n\n

要在静态上下文中调用任何非静态方法或变量,您需要首先使用构造函数或工厂构造对象,就像在类之外的任何地方一样。

\n