public class StaitcTest02{
public static void main(String[] args){
Chinese c1 = new Chinese("11111111","zhang","中国");
System.out.println(c1.idCard);
System.out.println(c1.name);
System.out.println(c1.country);
c1 = null; //当c1为空引用,不会出现空指针异常,因为静态变量不需要对象的存在,
System.out.println(c1.country); //中国
System.out.println(c1.idCard); //NullPointerException
}
}
class Chinese{
String idCard;
String name;
static String country;
public Chinese(){
}
public Chinese(String s1, String s2, String s3){
idCard = s1;
name = s2;
country = s3;
}
}
结论:
空引用访问静态不是空指针异常
当c1为空引用,不会出现空指针异常,因为静态变量不需要对象的存在,
System.out.println(c1.country),当代码在运行时,还是执行的是System.out.println(Chinese.country);
空指针异常的发生条件:
当”空引用“访问“实例”相关的,会发生空指针异常;