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

Java类被加载时执行的顺序问题

2010-01-07 10:55 363 查看
public class Parent

{

//1

static int a = 1;

//2

static

{

a = 10;

System.out.println("parent static code");

}

//4

public Parent()

{

System.out.println("Parent constructor");

System.out.println("Parent a=" + a);

}

public static void main(String[] args)

{

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

Parent c = new Child();

}

}

class Child extends Parent

{

static int a = 2;

//3

static

{

a = 20;

System.out.println("child static code");

}

//5

public Child()

{

System.out.println("Child constructor");

System.out.println("Child var a=" + a);

}

}

执行结果:

run:

parent static code

***************

child static code

Parent constructor

Parent a=10

Child constructor

Child var a=20

BUILD SUCCESSFUL (total time: 0 seconds)

Java
语言是动态链接的,只有在需要的时候才去加载java类,在加载java类的时候,首先执行类里面的static代码块,然后进入main入口函数,调用
子类的构造函数,生成子类的对象,子类被加载,调用子类的static代码块,然后开始调用子类的构造函数,调用之前要是检查到父类还没实例化,前去调用
父类的构造函数,保证父类实例化完毕了再去调用子类的构造函数,在子类构造函数中第一句可以用super()调用父类的构造函数感觉像是重新实例化了一个
对象!

现在将程序的入口从父类中转移到子类中,我们再看一下输出的执行流程。。。

class Parent

{

//1

static int a = 1;

//2

static

{

a = 10;

System.out.println("parent static code");

}

//4

public Parent()

{

System.out.println("Parent constructor");

System.out.println("Parent a=" + a);

}

}

public class Child extends Parent

{

static int a = 2;

//3

static

{

a = 20;

System.out.println("child static code");

}

//5

public Child()

{

System.out.println("Child constructor");

System.out.println("Child var a=" + a);

}

public static void main(String[] args)

{

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

Parent c = new Child();

}

}

执行结果:

run:

parent static code

child static code

***************

Parent constructor

Parent a=10

Child constructor

Child var a=20

BUILD SUCCESSFUL (total time: 0 seconds)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: