java对象初始化的顺序

Java代码

  1. public class Son extends Father {

  2. String value = null;//2

  3. public Son() {

  4. super(); //1

  5. System.out.println("Son:  " + value);//3

  6. }

  7. public static void main(final String[] args) {

  8. new Son();

  9. }

  10. }

  11. class Father {

  12. public Father() {

  13. if (this instanceof Son) {

  14. Son lower = (Son) this;

  15. lower.value = "test";

  16. }

  17. }

  18. }

  19. class Father {

  20. public Father() {

  21. if (this instanceof Son) {

  22. Son lower = (Son) this;

  23. lower.value = "test";

  24. }

  25. }

  26. }

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

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

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

评论

h
hw_7864

⭐️ Admin快速开发: https://show.cool-admin.com/

赞 0
h
hw_7864

⭐️ 官方文档: https://cool-js.com

赞 0
h
hw_7864

⭐️ chatgpt在线体验: https://cool-js.com/ai/chat-vip/index.html?r=helloworld

赞 0