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

18

在面向对象的编程范式中,静态方法只能访问静态变量和静态方法。如果是这样,那么一个明显的问题就出现了,即使Java中的main()方法明确声明为public static void,它怎么能访问非静态成员(变量或方法)呢?


你是怎么得出主方法可以访问实例变量和方法的结论的? - Laf
7个回答

30

主方法也无法访问非静态成员。

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

但是,无论是静态方法还是非静态方法都无法访问非静态成员[如果您像上面的示例中那样使用Snippet.instanceMethod()而不是通过实例化对象:new Snippet().instanceMethod()]。那么为什么所有人都对静态方法无法访问非静态成员感到烦恼呢? - Haider

14
通过创建该类的一个对象。
public class Test {
    int x;

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

5

main() 方法无法访问非静态变量和方法,在尝试这样做时会出现“无法从静态上下文引用非静态方法”的错误。

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

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

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


Desmond,你能否给出一个例子来说明你的答案吗? - joekevinrayan96
@JoeKevinRayan 给你.. 公共类MyClass { int x = 10; public static void main(String args[]) { System.out.println("x" + x); //不允许 System.out.println("x-" + new MyClass().x); //允许 } } - Zoran777

2
YourClass inst = new YourClass();
inst.nonStaticMethod();
inst.nonStaticField = 5;

2
你需要实例化你想要访问的对象。
例如:
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());
  }
}

1

通过对象的引用。

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

0

你必须创建一个类的实例来引用实例变量和方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接