阅读时间: 3分钟
大家在写code的时候,都有机会遇到在static main method中要call其他不是static method的method,
一不小心就会出现报错。
很多人未必去深究原因,找到解决方法就算,即使有多年经验的老手也未必知道是为什么。
报错的原因是因为class内的static method/ static variable不算是物件,只是class的其中一个成员而已。
由于它不是物件,所以不能去直接接触其他物件啦。
而static的method只能够调用同类或者物件(Object)。
要解决这个问题,可以使用以下方法。
public class Test1 { public String get() { return "123"; } public static void main(String[] args) { Test1 c = new Test1(); //要创建一个新的class物件(Object) String string = c.get(); //利用物件来召唤不是static的method System.out.print(string); }}