风雨无阻

java初始化顺序

在一个类里,初始化的顺序是由变量在类内的定义顺序决定的。即使变量定义大量遍布于方法定义的中间,那些变量仍会在调用任何方法之前得到初始化——甚至在构建器调用之前。例如:
class Tag {
  Tag(int marker) {
    System.out.println("Tag(" + marker + ")");
  }
}

class Card {
  Tag t1 = new Tag(1); // 先初始化t1
  Card() {
    // Indicate we're in the constructor:
    System.out.println("Card()");
    t3 = new Tag(33); // Re-initialize t3
  }
  Tag t2 = new Tag(2); // 然后初始化t2
  void f() {
    System.out.println("f()");
  }
  Tag t3 = new Tag(3); // 接着初始化t3
}

public class OrderOfInitialization {
  public static void main(String[] args) {
    Card t = new Card();
    t.f(); // Shows that construction is done
  }
}

它的输入结果如下:
"Tag(1)",
   "Tag(2)",
   "Tag(3)",
   "Card()",
   "Tag(33)",
   "f()"
// 以下是人综合例子:
//总的原则:先静态后动态,先定义初始化,后构造函数初始化
/**
   * 实例化Child对象时
   * 先父类静态成员初始化,后子类静态成员初始化
   * 然后是父类成员,父类构造函数,最后是子类
   * 成员,子类构造函数
*/

class Parent {
 private static int s = getS("父类静态成员");

 private int num = getNum();

 public Parent() {
  System.out.println("父类构造函数");
 }

 private static int getS(String string) {
  System.out.println(string);
  return 47;
 }

 public int getNum() {
  System.out.println("父类私有成员");
  return num;
 }

 public static void setS(int s) {
  Parent.s = s;
 }

}

class Child extends Parent {
 private int num = prt("子类私有成员");

 private static int s = getS("子类静态成员");

 public static void setS(int s) {
  Child.s = s;
 }

 public Child() {
  System.out.println("子类构造函数");
 }

 public void setNum(int num) {
  this.num = num;
 }

 private int prt(String string) {
  System.out.println(string);
  return 5;
 }

 public static int getS(String string) {
  System.out.println(string);
  return s;
 }
}


public class Tee {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Child c = new Child();
  c.setNum(100);

  // 为什么输出的是0
  System.out.print(c.getNum());

//  Child cStatic = new Child();
//  cStatic.setS(100);
//  System.out.println(cStatic.getS("s"));
     


 }

}

最后输出结果:
父类静态成员
子类静态成员
父类私有成员
父类构造函数
子类私有成员
子类构造函数
父类私有成员
0

posted on 2008-03-12 15:09 秋枫故事 阅读(360) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 
<2008年3月>
2425262728291
2345678
9101112131415
16171819202122
23242526272829
303112345

导航

统计

常用链接

留言簿(2)

随笔分类

随笔档案

新闻档案

搜索

最新评论

阅读排行榜

评论排行榜