从一道经典面试题说起,
public class HaHa {
public static void haha(){
System.out.println("haha");
}
public static void main(String[] args){
((HaHa)null).haha();
}
}
打印结果 haha。
这段题考查两点知识,java的空指针异常和静态方法。
1,NullPointerException
Thrown when an application attempts to use null in a case where an object is required. These include:
Calling the instance method of a null object.
Accessing or modifying the field of a null object.
Taking the length of null as if it were an array.
Accessing or modifying the slots of null as if it were an array.
Throwing null as if it were a Throwable value.
Applications should throw instances of this class to indicate other illegal uses of the null object. NullPointerException objects may be constructed by the virtual machine as if suppression were disabled and/or the stack trace was not writable.
这段话表明只有在使用空对象时,才会抛出空指针异常。而上面的写法并没有调用对象的方法。
2,static修饰的方法是静态方法。静态方法可通过类来调用,也可通过对象调用,即使使用对象调用,它的入口也在类上。