Chinaunix首页 | 论坛 | 博客
  • 博客访问: 157489
  • 博文数量: 76
  • 博客积分: 1513
  • 博客等级: 上尉
  • 技术积分: 755
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-25 15:15
文章分类

全部博文(76)

文章存档

2012年(2)

2011年(74)

我的朋友

分类: Java

2011-11-27 14:33:24

初始化语句块{}先于constructor初始化。(只要构造了类的一个对象,初始化块{}就会被执行,而且初始化块{}先于构造函数执行)。

  1. public class A {
  2. {
  3.    System.out.println("hello");
  4. }
  5. A()
  6. {
  7.    System.out.println("constructor");
  8. }
  9.     {
  10.        System.out.println("test");
  11.     }
  12.     public static void main(String[] args)
  13.     {
  14.         A a=new A();
  15.     }
  16. }

output:

hello
test
constructor

  1. public class Insect {
  2. private int i=9;
  3. protected int j;
  4. Insect()
  5. {
  6.    System.out.println("i="+i+","+"j="+j);
  7.    j=39;
  8. }
  9. private static int x1=printInit("static Insect.x1 initialized");
  10. static int printInit(String s)
  11. {
  12.    System.out.println(s);
  13.    return 47;
  14. }
  15. int a=print(88);
  16. int print(int b)
  17. {
  18.    System.out.println(b);
  19.    return b;
  20. }
  21. }

  22. public class Beetle extends Insect{
  23. private int k=printInit("Beetle.k initialized");
  24. Beetle()
  25. {
  26.    System.out.println("k="+k);
  27.    System.out.println("j="+j);
  28.   
  29. }
  30. private static int x2=printInit("Beetle.x2 initialized");
  31. public static void main(String[] args)
  32. {
  33.    System.out.println("Beetle constructor");
  34.    Beetle b=new Beetle();
  35. }

  36. }

output:

static Insect.x1 initialized
Beetle.x2 initialized
Beetle constructor
88
i=9,j=0
Beetle.k initialized
k=47
j=39

编译流程:

     1.main(),在执行main()里面的代码前,先对static初始化。从父类到子类,找到x1x2,输出 “static Insect.x1 initialization”” static Insect.x1 initialization”。(P.S 先初始化static,再初始化non-static)。

     2.main()里面的代码,输出”Beetle consturctor”

    3.Beetle(),找到父类Insect(),先初始化其父类。(P.S 先初始化变量,再初始化方法)。

     4.初始化Insecti等于9j等于0,然后是Insect()。(P.S 由于static不属于任何对象,而是属于某一个类,所以不需要再次初始化)。

     5.初始化Beetle,输出k,最后是Beetle()

阅读(849) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~