你的位置:首页 > Java教程

[Java教程]java 初始化顺序


java 变量类型如下:

实例变量;

类变量;

初始化途经如下:

实例变量

  --声明时,初始化;

  --非静态初始化块内,初始化;

  --构造函数内,初始化;

实例1:

public class bean1 {		int d;	int e;	int c;	int b;	int f;		{		c = 3;	}	int a = 1;		{		b = 2;	}		public bean1() {						d = 4;		f = 5;		e = 6;	}		public int geta() {						return a;		}	}

javap -c bean1.class 查看反汇编代码如下:

Compiled from "bean1.java"public class initialization.bean1 { int d; int e; int c; int b; int f; int a; public initialization.bean1();  Code:    0: aload_0    1: invokespecial #1         // Method java/lang/Object."<init>":()V    4: aload_0    5: iconst_3  //初始化c    6: putfield   #2         // Field c:I    9: aload_0   10: iconst_1  //初始化a     11: putfield   #3         // Field a:I   14: aload_0   15: iconst_2  //初始化b   16: putfield   #4         // Field b:I   19: aload_0   20: iconst_4  //初始化d   21: putfield   #5         // Field d:I   24: aload_0   25: iconst_5   26: putfield   #6         // Field f:I   29: aload_0   30: bipush    6   32: putfield   #7         // Field e:I   35: return public int geta();  Code:    0: aload_0    1: getfield   #3         // Field a:I    4: ireturn}

结论:实例变量的初始化均在public initialization.bean1()当中完成,无论是在声明时直接初始化,还是在代码块当中初始化,本质均在构造函数里面进行初始化,在构造函数当中的初始化顺序取决于在 定义直接初始化和代码块初始化中的顺序。

类变量

  --声明时,初始化;

  --静态初始化块内,初始化;

实例2:

package initialization;public class bean2 {		static int d;	static int e = 5;	static int c;	int b;	int f;	int a = 1;	static {		c = 3;		System.out.println("hello,static");			}		{		b = 2;		System.out.println("hello");	}	static {		d = 4;			}		public bean2() {						f = 6;	}		public int geta() {						return a;		}	}

新建bean2实例时,输出如下:

hello,statichello

静态代码块是主动执行的,需要在项目启动的时候就初始化;

javap -c bean2.class 查看反汇编代码如下:

Compiled from "bean2.java"public class initialization.bean2 { static int d; static int e; static int c; int b; int f; int a; public initialization.bean2();  Code:    0: aload_0    1: invokespecial #1         // Method java/lang/Object."<init>":()V    4: aload_0    5: iconst_1	//初始化a    6: putfield   #2         // Field a:I    9: aload_0   10: iconst_2	//初始化b   11: putfield   #3         // Field b:I   14: aload_0   15: bipush    6   17: putfield   #4         // Field f:I   20: return public int geta();  Code:    0: aload_0    1: getfield   #2         // Field a:I    4: ireturn static {};  Code:    0: iconst_5	//初始化e    1: putstatic   #5         // Field e:I    4: iconst_3	//初始化c    5: putstatic   #6         // Field c:I    8: iconst_4	//初始化d    9: putstatic   #7         // Field d:I   12: return}

结论:  实例变量的初始化均在public initialization.bean2()当中完成,无论是在声明时直接初始化,还是在代码块当中初始化,本质均在构造函数里面进行初始化,在构造函数当中的初始化顺序取决于在 定义直接初始化和代码块初始化中的顺序;

   类变量在static {}中完成,且初始顺序以代码中顺序为主,类变量在实例变量前执行;

关于java final可以查看:http://www.cnblogs.com/dolphin0520/p/3736238.html