Java静态绑定-null问题

    前两篇文章分析了静态绑定和动态绑定的问题,大家要是觉着不过隐,下面的问题一道题更能充分说明静态绑定

类StaticTest中有两个方法,一个是静态的一个是非静态的。当用 StaticTest staticTest=null;分别调用两个方法会有什么输出呢?且看如下代码

package binding;

public class StaticTest {
    public static void staticTest(){
        System.out.println("This is a staticTest");
    }

    public void test(){
        System.out.println("This is a nonstatic Test");
    }
    public static void main(String args[]){
        StaticTest staticTest=null;
        staticTest.staticTest();
        staticTest.test();

    }
}

输出结果是:


哈哈,看见了吧。静态方法能够正常输出,非静态方法报了空指针异常。

因为staticTest在编译的时候就会指向staticTest(),不管实例化是null还是子类对象,只于声明对象有关

猜你喜欢

转载自blog.csdn.net/jerry_player/article/details/80558045