從一道經典面試題說起,
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修飾的方法是靜態方法。靜態方法可通過類來調用,也可通過對象調用,即使使用對象調用,它的入口也在類上。