什么是静态变量?
有statlc的变量叫做静态变量
静态变量在类加载时初始化,不需要new对象,静态变量的空间就开出来了。静态变量存储在方法区
什么时候变量声明为实例的,什么时侯声明为静态的?
如果这个类型的所有对象的某个展性值都是一样的。不建议定义为实例变量。费内存空间,建议定义为类级别特征,定义为静态变量,在方法区中只保留一份。节省内存开销
静态变量会发生空指针现象吗?
静态的都是类相关的,访问时用类名.方法名的方式访问,不需要new对象,即没有空指针异常的发生
public class Student {
int id;
String name;
static String country="Chinese";
public Student(){
}
public Student(int a,String b){
id =a;
name=b;
}
}
public class StudentText {
public static void main(String args[]) {
System.out.println(Student.country);
Student st=new Student(1234,"张三");
System.out.println(st.name);
System.out.println(st.id);
Student st1=new Student(5678,"李四");
System.out.println(st1.name);
System.out.println(st1.id);
}
}
Chinese
张三
1234
李四
5678