我做了试验,把 void print() 里的语句 System.out.println("storage(s) = " + storage(s)); 注释掉,然后加 static ,变成static void print() { } ,这样就不出错。初步想的原因是 storage() 不是 static 的所以会出错, 而 int storage(String s) 可以加static 的原因是 里面没有语句连接到 non-static 的方法。 可是,迷惑的问题来了, 我 声明 static int storage(String s) 这样还是不行,这样我已经让 static void print() 里的语句用到的方法都是 static 的了,可是为何还出以上的错误呢??谢谢!!!
main方法之所以可以先执行,也是因为被声明为static.
public class Test1 {
String s = "Hello, World!";
// 【问题1】 如果这里改为 static int 没问题,依旧正常运行
int storage(String s) {
return s.length() * 2;
} // 【问题2】 如果这里改为 static void 就出错,错误见后面
void print() {
System.out.println("storage(s) = " + storage(s));
} public static void main(String[] args) {
Test1 st = new Test1();
st.print();
}
}时,没有问题.
为什么把 void print() 里的语句 System.out.println("storage(s) = " + storage(s)); 注释掉,然后加 static ,变成static void print() { } ,这样就不出错?
是因为当你加上static时,变成static void print() 此时print()方法变为static的.而在static方法中是不可以调用non-static非static方法和数据成员的!注意.你已经知道
"初步想的原因是 storage() 不是 static 的所以会出错, 而 int storage(String s) 可以加static 的原因是 里面没有语句连接到 non-static 的方法。 "但是你没有想到数据成员.也就是String s
{
public static void prt()
{
System.out.println("static a = " + a);
//System.out.println("non-static b = " + b); //!!!为什么这里会出错??
}
public static void main(String[] args)
{
prt();
}
public static double a = 2.2;
public double b = 2.2; //因为b是non-static数据
}至于原理.楼上的jackkui(键盘上的武士)和 cold_blooded(小熊) 已经说的很清楚.你可以试着理解一下.在楼主的例子中,把String s = "Hello, World!";改为 static String s = "Hello,world" 一切问题迎刃而解~~建议楼主看看thinking in java :)
Cannot make a static reference to the non-static field s at Test1.print(Test1.java:14)
at Test1.main(Test1.java:19)
Exception in thread "main" //错误信息已经很明显了,不能在非静态区域里引用静态函数.