`

java对象初始化的顺序

阅读更多



public class Son extends Father {

    String value = null;//2

    public Son() {
        super();  //1
        System.out.println("Son:  " + value);//3
    }

    public static void main(final String[] args) {
        new Son();
    }
}


class Father {

    public Father() {
        if (this instanceof Son) {
            Son lower = (Son) this;
            lower.value = "test";
        }
    }
}


class Father {

    public Father() {
        if (this instanceof Son) {
            Son lower = (Son) this;
            lower.value = "test";
        }
    }
}




这个的结果是 null
步骤1  设置为test
步骤2  设置为null
步骤3 打印出来null

如果 不是   String value = null ; 只是   String value;
步骤1  设置为test
步骤2  不做任何事情,因为已经有值了,不用设置为默认的null值了
步骤3 打印出来null


所以  一个字段不设置值 和 设置为null  是有区别的。


0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics