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

在Java中通过main方法访问非静态成员,java,Java,作为面向对象范例中的规则,静态方法只能访问静态变量和静态方法。如果是这样的话,一个明显的问题就出现了:Java中的main()方法如何能够访问非静态成员(变量或方法),即使它是专门公开的静态void 通过创建该类的对象 public class Test { int x; public static void main(String[] args) { Test t = new Test(); t.x = 5; } } 通过对对象的引用

作为面向对象范例中的规则,静态方法只能访问静态变量和静态方法。如果是这样的话,一个明显的问题就出现了:Java中的main()方法如何能够访问非静态成员(变量或方法),即使它是专门公开的静态void

通过创建该类的对象

public class Test {
    int x;

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

通过对对象的引用

public class A {
    private String field;


    public static void main(String... args) {
        //System.out.println(field); <-- can not do this
        A a = new A();
        System.out.println(a.field); //<-- access instance var field that belongs to the instance a 
    }
}
公共A类{
私有字符串字段;
公共静态void main(字符串…参数){

//System.out.println(field);必须创建类的实例才能引用实例变量和方法。

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

您必须实例化要访问的对象

比如说

public class MyClass{

  private String myData = "data";

  public String getData(){
     return myData;
  }

  public static void main(String[] args){
     MyClass obj = new MyClass();
     System.out.println(obj.getData());
  }
}
main()方法无法访问非静态变量和方法,当您尝试这样做时,将得到“无法从静态上下文引用非静态方法”

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

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


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

您是如何得出主方法可以访问实例变量和方法的结论的?嗨,Desmond,您是否可以您的答案有一个例子吗?但是任何方法,无论是静态的还是非静态的,都不能访问非静态成员[如果您在上面的示例中像
Snippet.instanceMethod()
那样,而不是通过实例化一个对象:
newsnippet().instanceMethod()
].那么,为什么所有关于静态方法的大惊小怪都无法访问非静态成员呢?
public class MyClass{

  private String myData = "data";

  public String getData(){
     return myData;
  }

  public static void main(String[] args){
     MyClass obj = new MyClass();
     System.out.println(obj.getData());
  }
}