当在空引用上调用某个方法时,它会抛出NullPointerException,但是对于静态方法,我们可以使用强制转换表达式来实现。请参阅下面的示例-
示例public class Tester {
public static void display(){
System.out.println("display");
}
private void print() {
System.out.println("print");
}
public static void main(String[] args) {
//Scenario 1:
//Calling a method on null reference
//causes NullPointerException
try {
Tester test = null; test.print();
}catch(Exception e) {
System.out.println(e.getMessage());
}
//Scenario 2:
//Static method can be invoked
//on a null object by using the casting expression
((Tester)null).display();
}
}
输出结果null
display
笔记方案1演示了导致NullPointerException的代码。
方案2通过评估空对象上的类名演示了静态方法的使用。