java进行对象初始化的过程

来源:互联网 发布:安装Linux命令行模 编辑:程序博客网 时间:2024/06/14 04:48
public class Lesson {    String name;    int time;    public Lesson(String name,int time) {        // TODO Auto-generated constructor stub        this.name=name;        this.time=time;    }    static{        System.out.println("执行static代码块!");    }    {        System.out.println(this.name+",,"+this.time);    }    public void show(){        System.out.println(this.name+",,,"+this.time);    }    public static void main(String[] args) {        // TODO Auto-generated method stub        Lesson p = new Lesson("math", 48);              p.show();    }}

运行结果为:

执行static代码块!
null,,0
math,,,48

说明先执行static代码块,再执行构造代码块,然后执行构造函数。

Lesson p = new Lesson("math", 48);执行这句话的时候,计算机做的工作顺序为:

  1. 先将Lesson.class加载到内存当中;
  2. 执行该类的static代码块。如果有的话;
  3. 在堆内存中开辟空间,分配内存地址;
  4. 在堆内存中尽力对象的特有属性,并进行默认初始化;
  5. 对属性进行显示初始化;
  6. 对属性进行构造代码块初始化(也就是执行构造代码块中的内容);
  7. 对属性进行构造函数初始化;
  8. 将内存地址赋给栈内存中的p变量;

0 0
原创粉丝点击