随笔-14  评论-1  文章-4  trackbacks-0

//: c06:Beetle.java
// The full process of initilization.
// first load base-class, and static filed will be initilized:
class Insect {
 int i = 9;
 int j;
 Insect() {
  prt("i = " + i + ", j = " + j);
  j = 39;
 }
 static int x1 = prt("static Insect.x1 initilized");
 static int prt(String s) {
  System.out.println(s);
  return 47;
 }
}
// then load derived class, & the static fileds will be initilized:
// after this, u can create object now, first of all
// all the base fileds will be set to default value(reference
// will be set to "null"
// then call the base-class constructor --> call derived class
// constructor.
public class Beetle extends Insect {
 int k = prt("Beetle.k initilized");
 Beetle() {
  prt("k = " + k);
  prt("j = " + j);
  j = 56;
 }
 static int x2 = prt("static Beetle.x2 initilized");
 public static void main(String[] args) {
  prt("Beetle constructor");
  Beetle b = new Beetle();
 }
}///:~

//: c6/P23.java
// class loaded and initilization
public class P23 extends Beetle {
 int m = prt("P23.m initilized");
 P23() {
  prt("m = " + m);
  prt("j = " + j);
 }
 // will initilized after the static fileds of Beetle:
 static int x3 = prt("static P23.x3 initilized");
 public static void main(String[] args) {
  // begin to run base-class constructor
  prt("P23 constructor");
  P23 p = new P23();
 }
}

Ressult of run P23:

// initilized the base-class and the derived-class static fileds:
static Insect.x1 initilized
static Beetle.x2 initilized
static P23.x3 initilized
// set default value to the non-static fileds
// call the very class's constructors
// work like this one by one, and class P23 at last:
P23 constructor
i = 9, j = 0
Beetle.k initilized
k = 47
j = 39
P23.m initilized
m = 47
j = 56
=========================
总结:
1) when run the derived-class, jvm first load all relevant class object, at this time will do:

    a. initized the base-class and the derived-class static fields

    b. and then when new the derived class instance, e,g new P23(), need set default value to the non-static fields and call the just class's constructors for base class, and trun to the derived class, i.e. P23 at last.

     work like this one by one

posted on 2008-06-27 00:35 大胃王的BLOG 阅读(291) 评论(0)  编辑  收藏

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


网站导航: