轉:
我在一個類中寫了一個public void getDate()方法和一個main方法,在main方法中直接調用getDate()方法,於是就出現了這個錯誤提示。后來實例化類,再用實例化的類調用getDate()方法就沒問題了。
在靜態方法中,不能直接訪問非靜態成員(包括方法和變量)。
因為,非靜態的變量是依賴於對象存在的,對象必須實例化之后,它的變量才會在內存中存在。例如一個類 Student 表示學生,它有一個變量 String address。如果這個類沒有被實例化,則它的 address 變量也就不存在。而非靜態方法需要訪問非靜態變量,所以對非靜態方法的訪問也是針對某一個具體的對象的方法進行的。對它的訪問一般通過 objectName.methodName(args......) 的方式進行。
而靜態成員不依賴於對象存在,即使是類所屬的對象不存在,也可以被訪問,它對整個進程而言是全局的。因此,在靜態方法內部是不可以直接訪問非靜態成員的。
Static methods cannot call non-static methods. An instance of the class is required to call its methods and static methods are not accociated with an instance (they are class methods). To fix it you have a few choices depending on your exact needs.
/** * Will not compile */ public class StaticReferenceToNonStatic { public static void myMethod() { // Cannot make a static reference // to the non-static method myNonStaticMethod(); } public void myNonStaticMethod() { } } /** * you can make your method non-static */ public class MyClass { public void myMethod() { myNonStaticMethod(); } public void myNonStaticMethod() { } } /** * you can provide an instance of the * class to your static method for it * to access methods from */ public class MyClass { public static void myStaticMethod(MyClass o) { o.myNonStaticMethod(); } public void myNonStaticMethod() { } } /** * you can make the method static */ public class MyClass { public static void myMethod() { f(); } public static void f() { } }