[code="java"]
public class Test1 {
public static void helloStatic(){
System.out.println("Hello Static ...");
}
public void helloDynamic(){
System.out.println("Hello Dynamic ...");
}
public static void main(String[] args) {
Test1 t1 = null;
t1.helloStatic();
t1.helloDynamic();
}
}
[/code]
[size=medium]上面的代码调用静态的就可以,调用非静态的方法代码就报错空指针。能解释下为什么吗?[/size]
Test1 t1 = null;
t1.helloStatic();
t1.helloDynamic();
(1)t1没有初始化,helloDynamic不是静态的,必须报空指针,没有什么疑义。
(2)helloStatic()是静态方法,和类定义与否没有关系。t1.helloStatic()在调用时编译器检测到时静态的,相当于Test1.helloStatic(),就不去理会t1什么事。
t1是null啊,不报空指针报啥?
静态方法是属于这个类的,不属于任何对象,非静态方法是属于该类的对象的
static方法在main方法调用时会在内存生成一份拷贝,所以它能够在它的类的任何对象创建之前被访问,而非静态的方法只能被实例化的对象访问。
[quote]Test1 t1 = null; [/quote]
t1不是任何类的实例,instanceof关键字是判断某个对象是某个类的实例;
getClass是对象的方法,t1为null,所以也不能调用。