您的位置:首页 > 编程语言 > Java开发

java初始化顺序

2016-07-10 17:25 357 查看

本类中的初始化顺序

public class A {
private int a = show(1);
static{
System.out.println("static A");
}
public A(){
System.out.println("A--无参构造器");
}
private int show(int i2) {
System.out.println("A:"+i2);
return i2;
}
public static void main(String[] args) {
A a = new A();
}
}
//输出结果为:
//static A
//A:1
//A--无参构造器


由程序的运行结果可知一个类中的初始化顺序为:

静态方法或静态块(它们之间没有优先顺序,以实际出现的顺序为准)。

非静态代码(变量或代码块)

构造方法

子父类中的初始化顺序

public class A {
private int a = show(1);
static{
System.out.println("static A");
}
public A(){
System.out.println("A--无参构造器");
}
private int show(int i2) {
System.out.println("A:"+i2);
return i2;
}
}

public class B extends A{
private int a = show(2);
static{
System.out.println("static B");
}
public B(String name){
System.out.println("B--有参构造器:"+name);
}
private int show(int i2) {
System.out.println("B:"+i2);
return i2;
}
public static void main(String[] args) {
B b1 = new B("b1");
}
}

//执行结果为:;
//static A
//static B
//A:1
//A--无参构造器
//B:2
//B--有参构造器:b1


由上例可知在存在继承关系的类的初始化的顺序为:

父类的静态代码

子类的静态代码

父类的非静态代码

父类的构造器

子类的非静态代码

子类的构造器

一道经典的关于初始化顺序的面试题

public class Test {
public static int k=0;
public static Test t1=new Test("t1");
public static Test t2=new Test("t2");
public static int i=print("i");
public static int n=99;
private int a=0;
public int j=print("j");
{
print("构造块");
}
static
{
print("静态块");
}
public Test(String str)
{
System.out.println((++k)+":"+str+"   i="+i+"    n="+n);
++i;++n;
}
public static int print(String str)
{
System.out.println((++k)+":"+str+"   i="+i+"    n="+n);
++n;
return++i;
}
public static void main(String args[])
{
Test t=new Test("init");
}
}
//执行结果为:
1:j   i=0    n=0
2:构造块   i=1    n=1
3:t1   i=2    n=2
4:j   i=3    n=3
5:构造块   i=4    n=4
6:t2   i=5    n=5
7:i   i=6    n=6

4000
8:静态块   i=7    n=99
9:j   i=8    n=100
10:构造块   i=9    n=101
11:init   i=10    n=102


分析执行过程:

1.加载public static int k=0;

2.加载public static Test t1=new Test(“t1”);这时需要实例化t1,因此下一步要执行非静态代码和构造器。

3.加载private int a=0;

4.加载public int j=print(“j”);

5.加载public static int print(String str) 这个方法。

6.加载构造器public Test(String str)

7.加载public static Test t2=new Test(“t2”); 重复2-6步

8.继续加载类的静态属性。加载public static int i = print(“i”);并执行完毕。

9.继续加载类的静态属性。加载public static int n=99;

10.加载主函数,加载Test t=new Test(“init”);

11.重复2-6步直至结束。

这道题十分考验基础而且还没涉及继承的情况,现在我只从表面理解初始化顺序,相信将来研究了JVM的初始化原理,就能更深入的理解它。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息