java中((NULL)null).say()能运行吗?

"talk is cheap show me the code"

先上代码,下面代码能运行吗?

public class NULL {
    public static void say() {
        System.out.println("null say: haha");
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ((NULL)null).say();
    }

}

作者看到这个时,没经过思考就觉得不能,而且还觉得这个问题很扯蛋!答案是:能运行,输出:

null say: haha

所以特此记录,不知有没有跟我一样想的。这里解释一下:
第一,null值可以转换为任何java类型,所以任何类型对null强转都是合法的,比如(String)null。但null强转后是无效对象,返回值还是null。
第二,static方法的调用(这里的say方法)是和类名绑定的,不借助对象进行访问,所以这里能正确输出,反过来,去掉static修饰符之后,使用null调用编译都不会通过!

你可能感兴趣的:(java中((NULL)null).say()能运行吗?)