public class mytest {
static String str="hello";
mytest getMytest(){
return null;
}
public static void main(String[] args) {
System.out.println(new mytest().getMytest().str);
}}
这道题目结果为什么不出现异常呢?结果为“hello”.
我打印new mytest().getMytest()为null
static String str="hello";
mytest getMytest(){
return null;
}
public static void main(String[] args) {
System.out.println(new mytest().getMytest().str);
}}
这道题目结果为什么不出现异常呢?结果为“hello”.
我打印new mytest().getMytest()为null
无static是对象级的。所以输入为hello,去掉static会报空指针错误
因为static在你创建对象前已经初始化了!
static的变量 类来调用
非static的变量 对象来调用
这里虽然方法返回的对象为空,但是类是在的。
null 是一个对象的实例才有的东西,你从来不会有某个类是null,肯定是某个对象是null
而静态方式是不依赖于对象的实例的,换句话说,只要知道属于哪个类,就能访问类的静态方法
所以,虽然get方法返回了null,但其类型依然是mytest, 系统不需要根据null,也不需要访问null的任何东西,只需要知道null是mytest类型的就可以直接访问了。所以,不会出空指针问题。
public class Mytest {
static String str="hello";
Mytest getMytest(){ return null;
}
public static void main(String[] args) {
Mytest s=new Mytest();
Mytest ss=s.getMytest();
String sss=ss.str;
System.out.println(sss);
}
}