java初始化的顺序

来源:互联网 发布:testv淘宝店搜不到 编辑:程序博客网 时间:2024/05/22 21:24

java创建的顺序:
1.先初始化本类中的静态方法和函数
2.再执行构造函数
3.执行构造函数时,有基类先运行基类(如果有基类,基类的构造顺序也是一样的)
4.运行完基类后,在依次初始化实例变量,最后运行剩下的构造器内容
5.在运行main函数(main函数也是static方法)

代码:

class Base{    static int a=1;    static int b;    int c=2;    public Base(){        System.out.println("Base  a="+a+" b="+b+" c="+c);        b=2;    }    void  show(int a){        System.out.println(a);    }}class Other{    public Other(String c) {        System.out.println(c);    }}public class Test7 extends Base{    static Other other1=new Other("static Other  other1");    public Test7() {        System.out.println("Test  a="+a+" b="+b);    }    Other other3=new Other("Other  other3");    static Other other2=new Other("static Other  other2");    public static void main(String[] args) {        Test7 test7=new Test7();        Test7 test8=new Test7();    }    static Other other4=new Other("static Other  other4");}

结果:
static Other other1
static Other other2
static Other other4
Base a=1 b=0 c=2
Other other3
Test a=1 b=2
Base a=1 b=2 c=2
Other other3
Test a=1 b=2

可以看见先执行static,而且只执行一遍,从a,b,c可以看出来成员初始在执行父类之后,在构造器其他操作之前。执行基类后再执行子类。

0 0
原创粉丝点击