一道美团的面试题:
public class NULL {
public static void print() {
System.out.println("NULL.print");
}
public static void main(String[] args) {
try {
((NULL) null).print();
} catch (NullPointerException e) {
System.out.println("NullPointerException");
}
}
}
运行结果:
初步猜测java中强制转换的原理为用转换类型指向被转换类型的引用,以上代码相当于:
public class NULL {
public static void print() {
System.out.println("NULL.print");
}
public static void main(String[] args) {
try {
NULL n = null;
n.print();
} catch (NullPointerException e) {
System.out.println("NullPointerException");
}
}
}
运行结果:
比较官方的说法正在查找中,未完待续…