轉載請註明出處,原文鏈接:https://blog.csdn.net/u013642500/article/details/80156306
【錯誤】
Non-static method '*' cannot be referenced from a static context
【翻譯】
在靜態上下文中不能引用非靜態方法'*'
【造成原因】
直接調用了其他包內的非靜態方法。
【舉例】
包 com.test.package1 中有類 TestMethod,該類中有非靜態方法 test()。
package com.test.Package1;
public class TestMethod {
public void test(){
// 方法內容
}
}
包 com.test.package2 中有類 Test,該類中某方法內引用包 com.test.package1 中 TestMethod 類的 test()方法。
package com.test.Package2;
import com.test.TestMethod;
public class Test {
public void testUseMethod(){
TestMethod.test();
// 此處報錯:Non-static method 'test()' cannot be referenced from a static context
}
}
【解決方法1】
將包 com.test.package1 中 TestMethod 類的非靜態方法 test() 改爲靜態方法。
package com.ssc.mt.magictower.Package1;
public class TestMethod {
public static void test(){ // 給test()方法添加關鍵字static
// 方法內容
}
}
【解決方法2】
引用包 com.test.package1 中 TestMethod 類的 test()方法時,先實例化一個 TestMethod 類的對象,再用對象引用方法。
package com.ssc.mt.magictower.Package2;
import com.ssc.mt.magictower.Package1.TestMethod;
public class Test {
public void testUseMethod(){
TestMethod testMethod = new TestMethod();
testMethod.test();
// 先實例化對象,再通過對象引用方法
}
}
【相關報錯】
錯誤:Static member '*' accessed via instance reference
造成原因:實例化對象後,通過對象引用了靜態方法。
解決方法1:直接通過類名引用方法。
解決方法2:將靜態方法改爲非靜態方法(刪去static關鍵字)。
【說明】
本文可能未必適用所有情形,本人尚屬初學者,如有錯誤或疑問請評論提出,由衷感謝!