代码解释对象的创建过程

为了写个实习日志,我还专门写代码测试了下对象的创建过程,囧。。。

首先看看测试的代码:

package com.test;

public class GrandFather {

static {
System.out.println("GrandFather's Static Block!");
}

private String grandFather = "This is grandFather!";

{
System.out.println("GrandFather's non Static Block!");
System.out.println(this.grandFather);
}

GrandFather() {
System.out.println("GrandFather's Constructor!");
}

}



package com.test;

public class Father extends GrandFather {

static {
System.out.println("Father's Static Block!");
}

private String father = "This is father!";

{
System.out.println("Father's non Static Block!");
System.out.println(this.father);
}

Father() {
System.out.println("Father's Constructor!");
}

}



package com.test;

public class Son extends Father {

static {
System.out.println("Son's Static Block!");
}

{
System.out.println("Son's non Static Block!");
System.out.println(this.son);
}

private String son = "This is son!";

Son() {
System.out.println("Son's Constructor!");
}

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

}


三个类,从上到下依次继承上一个类。
再让我们来看下运行结果:
GrandFather's Static Block!
Father's Static Block!
Son's Static Block!
GrandFather's non Static Block!
This is grandFather!
GrandFather's Constructor!
Father's non Static Block!
This is father!
Father's Constructor!
Son's non Static Block!
null
Son's Constructor!

分析:
GrandFather's Static Block!
Father's Static Block!
Son's Static Block!

从Son类的main方法开始运行,虚拟机查找Son.class文件,发现它有个父类,于是查找Father.class,又发现Father.class有父类,于是继续查找。终于找到了最上层的父类GrandFather.class。于是从顶到底依次执行其静态成员变量和静态块,此时类加载已经完成,对象已经创建,接下来要做的就是实例化了。

..........
GrandFather's non Static Block!
This is grandFather!
GrandFather's Constructor!
Father's non Static Block!
This is father!
Father's Constructor!
Son's non Static Block!
null
Son's Constructor!

从最上层父类到最底层子类依次执行一下几个步骤:
1、在堆中给对象分配存储空间。
2、给成员变量赋予初始值(0,false,null)。
3、按顺序依次执行非静态数据成员的赋予初始值和非静态块。
4、执行构造函数。

........
Father's non Static Block!
This is father!
........
Son's non Static Block!
null
........
Son中为什么会输出为null呢?
因为我把非静态块和赋予非静态成员变量的的顺序对换了。非静态块在前。
我这样做有两个原因:
1、证明了在调用非静态块以前和非静态成员变量赋予初始值以前,非静态成员变量已经存在,并且赋予了默认值
2、证明了调用非静态块和非静态成员变量赋予初始值是同一优先级别的

总结:
对象创建过程应该是这样的:
1、即将装载某个类的时候,寻找这个类的class文件,如果有父类的话,就在寻找其父类的class文件,一直找到最顶层的父类。
2、从最顶层父类到最底层子类依次产生对象,执行对象中所有的静态成员变量和静态块
3、从最顶层父类到最底层子类依次执行如下步骤:
3.1 在堆上为类分配足够的存储空间
3.2 将该对象中所有数据设为默认值
3.3 按顺序执行该对象中非静态成员变量赋予初始值和非静态块
3.4 执行构造函数

PS:新手发帖,可能有误,如果有误,请拍板砖。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值