public class TestVarg{ static int b=2; public static void main(String[] args){ int a=1; System.out.println(a); System.out.println(b); } } 如上小程序,我写成 int b=2为什么程序报错,而写成static int b=2的时候,程序是正错的?
在static方法里面只能调用static变量,若是非static变量则必须通过一个对象来引用,如: int b=2; TestVarg tv=newTestVarg(); System.out.println(tv.b);
public class TestVarg {int b=2;TestVarg(){ System.out.println(b); }public static void main(String[] args){ int a=1; System.out.println(a); new TestVarg(); } }这样就可以了(没有在main中使用非static变量)
当为static int b=2时,b 不属于某一个类,他是静态变量,在什么方法中都可以访问,但是,如果只是int b=2的话,就只能先在别的方法中定义一个对象之后再访问b!
static是静态变量,不需要定义对象,就可以使用,就你下面的,可以直接输出system.out.printf 没有static的话,上面是属性,一定要定义一个变量,testwarg aa= new testwarg 这样才可以。
int b=2;
TestVarg tv=newTestVarg();
System.out.println(tv.b);
System.out.println(b);
}public static void main(String[] args){
int a=1;
System.out.println(a);
new TestVarg();
}
}这样就可以了(没有在main中使用非static变量)
没有static的话,上面是属性,一定要定义一个变量,testwarg aa= new testwarg 这样才可以。