Java子方法中static去掉之后的报错原因
看如下代码
class pingfang{ public static int pingfang(int x){ return x*x; }
public static void main(String args[]){ System.out.println(pingfang(5)); }
}
pingfang(int x)这个函数没有static的话会报错
Cannot make a static reference to the non-static method pingfang(int) from the type ..
因为一个类的静态方法在这个class文件被加载之后才可以由这个class类型对象来调用;而非静态方法需要一个实例对象(可能它还未被创建),所以为例避免在静态方法中调用一个还不存在的实例对象的非静态方法,编译器会直接阻止这个行为。
浙公网安备 33010602011771号