关于java初始化顺序的一个示例

public class Sample
{
public static void main(String[]args){
Bba
= new B();

System.out.println(
" ------------------------------- " );

Bbb
= new B();
}
};


class Target
{
public Target(Strings){
System.out.println(
" Target( " + s + " ) " );
}
};

class A
{

public static Targettd = new Target( " staticinA " );
static {
System.out.println(
" staticblockinA " );
}

{
System.out.println(
" non-staticblockinA " );
}

public Targetta = new Target( " inA " );
};

class B extends A
{
public Targettb = new Target( " inB " );
static {
System.out.println(
" staticblockinB " );
}
static public Targettc = new Target( " staticinB " );

{
System.out.println(
" non-staticblockinB " );
}

};


结果:
Target( static in A)
static block in A
static block in B
Target(
static in B)
non
- static block in A
Target(
in A)
Target(
in B)
non
- static block in B
-------------------------------
non
- static block in A
Target(
in A)
Target(
in B)
non
- static block in B



注意:
  1. All data fields are initialized to their default value (0, false, or null).

  2. All field initializers and initialization blocks are executed, in the order in which they occur in the class declaration.

  3. If the first line of the constructor calls a second constructor, then the body of the second constructor is executed.

  4. The body of the constructor is executed。


另外,可以看到:
先父类的static,后子类的static,然后父类的非static,再子类的非static。
static包括静态的字段和初始化块。
非static包括非静态字段和初始化块。
同级别的字段或初始化块的顺序就依赖于定义的先后了。

还有一点简单的,顺便提一下:
static的东东只在类装入的时候,执行一次。不是每次实例化一个对象时都执行。

顺便提第二点:在jdk5中因为支持可变参数列表所以,
public static void main(String...args) ... {}

是成立的。

另外,关于初始化问题参见:
http://www.javaworld.com/javaworld/jw-03-1998/jw-03-initialization.html?page=1

你可能感兴趣的:(java)