有趣的是,列出的两个答案都忽略了发问者正在使用静态方法的事实。因此,除非类类或成员变量也被声明为静态或静态引用,否则该方法将无法访问任何类或成员变量。这个例子:
public class MyClass { public static String xThing; private static void makeThing() { String thing = "thing"; xThing = thing; System.out.println(thing); } private static void makeOtherThing() { String otherThing = "otherThing"; System.out.println(otherThing); System.out.println(xThing); } public static void main(String args[]) { makeThing(); makeOtherThing(); }}会起作用的,但是,如果像这样,那就更好了……
public class MyClass { private String xThing; public void makeThing() { String thing = "thing"; xThing = thing; System.out.println(thing); } public void makeOtherThing() { String otherThing = "otherThing"; System.out.println(otherThing); System.out.println(xThing); } public static void main(String args[]) { MyClass myObject = new MyClass(); myObject.makeThing(); myObject.makeOtherThing(); }}


