您的位置:首页 > 编程语言 > Java开发

java----对象初始化及变量的缺省值

2013-08-17 00:21 169 查看
<---百草枯--->

qq:916923477<--->maooam;

对象初始化及变量的缺省值

初始化顺序的先静态对象,而后是非静态对象

1、第一次创建类的的对象或是调用类的静态方法/静态字段,会加载class文件

2、加载class文件后有关静态初始化的所有动作会执行

3、当用new创建对象时,首先在堆上为类对象分配足够存储空间

4、将这个存储空间清零,所有基本类型设置为缺省值,引用为NULL

5、执行所有出现于字段定义处的初始化动作

6、执行构造方法,当有继承时会涉及更多的动作。
示例代码:

public class StaticInitialization {
  public static void main(String[] args) {
    System.out.println("Creating new Cupboard() in main");
    new Cupboard();
    System.out.println("Creating new Cupboard() in main");
    new Cupboard();
    t2.f2(1);
    t3.f3(1);
  }
  static Table t2 = new Table();
  static Cupboard t3 = new Cupboard(); }
  class Bowl {
    Bowl(int marker) {
      System.out.println("Bowl(" + marker + ")");
    }
    void f(int marker) {
      System.out.println("f(" + marker + ")");
    }
  }
  class Table {
    static Bowl b1 = new Bowl(1);
    Table() {
      System.out.println("Table()");
      b2.f(1);
    }
    void f2(int marker) {
      System.out.println("f2(" + marker + ")");
    }
    static Bowl b2 = new Bowl(2);
  }
  class Cupboard {
    Bowl b3 = new Bowl(3);
    static Bowl b4 = new Bowl(4);
    Cupboard() {
      System.out.println("Cupboard()");
      b4.f(2);
    }
    void f3(int marker) {
      System.out.println("f3(" + marker + ")");   
    }
    static Bowl b5 = new Bowl(5);
}
运行结果:

"Bowl(1)",
"Bowl(2)",
  "Table()",
  "f(1)",
  "Bowl(4)",
  "Bowl(5)",
  "Bowl(3)",
  "Cupboard()",
  "f(2)",
  "Creating new Cupboard() in main",
  "Bowl(3)",
  "Cupboard()",
  "f(2)",
  "Creating new Cupboard() in main",
  "Bowl(3)",
  "Cupboard()",
  "f(2)",
  "f2(1)",
  "f3(1)"
结果分析:

在程序一开始加载的时候,就会先执行:

1、 static Table t2 = new Table();
2、 static Cupboard t3 = new Cupboard();
在执行1的时候又会跳转到class Table{}里面去,class Table{}里面又有static Bowl b1 = new Bowl(1);所以跳转到class Bowl{}执行它的构造方法,所以先输出Bowl(1);回到class Table{}继续往下面执行,继续执行Table后面的static Bowl b2 = new Bowl(2);所以又输出Bowl(2);然后就执行Table的构造方法;然后又执行b2.f(1);

总结:

先执行静态,再执行构造函数,然后就执行普通。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: