转载请注明出处,原文链接: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关键字)。
【说明】
本文可能未必适用所有情形,本人尚属初学者,如有错误或疑问请评论提出,由衷感谢!