通过Java中的main方法访问非静态成员
作为面向对象范例的规则,静态方法只能访问静态变量和静态方法。 如果是这样的话,就会出现一个明显的问题,即Java中的main()方法如何能够访问非静态成员(变量或方法),即使它是特定的public static void … !!!
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 Test { int x; public static void main(String[] args) { Test t = new Test(); tx = 5; } }
YourClass inst = new YourClass(); inst.nonStaticMethod(); inst.nonStaticField = 5;
main()方法无法访问非静态变量和方法,当您尝试这样做时,您将获得“无法从静态上下文中引用非静态方法”。
这是因为默认情况下,当您调用/访问方法或变量时,它实际上是访问this.method()或this.variable。 但是在main()方法或任何其他静态方法()中,尚未创建“this”对象。
从这个意义上说,静态方法不是包含它的类的对象实例的一部分。 这是实用程序类背后的想法。
要在静态上下文中调用任何非静态方法或变量,您需要首先使用构造函数或工厂构造对象,就像在类外部的任何位置一样。
通过引用对象。
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 } }
您必须实例化您要访问的对象。
例如
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()); } }
您必须创建该类的实例才能引用实例变量和方法。