Java知识积累——静态代码块,非静态代码块,构造器的执行顺序和次数

看如下程序

 1 class A {
 2    static{
 3       System.out.println("A static");
 4    }   
 5 
 6    {
 7       System.out.println("A not static"); 
 8    }   
 9 
10    public A(){
11       System.out.println("A new");
12    }
13 }
14 
15 class B extends A{
16    static{
17       System.out.println("B static");
18    }   
19 
20    {
21       System.out.println("B not static"); 
22    }  
23 
24    public B(){
25       System.out.println("B new");
26    }
27 } 
28 
29 public class MainTest {
30    public static void main(String[] args) {
31       A ab= new B();
32       ab= new B();
33    }
34 }

输出如下:

A static

B static

A not static

A new

B not static

B new

A not static

A new

B not static

B new

 

结论: 

静态代码块只有类首次加载进内存时调用一次,只此一次。

非静态代码块,每次创建对象时,会在构造函数之前被调用。

构造函数,每次创建对象时,最后调用。

创建子类对象时,先创建父类对象,再创建子类对象。

posted @ 2013-01-31 11:25  FlameRen  阅读(1173)  评论(8编辑  收藏  举报