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

来源:互联网 发布:大数据立法现状 编辑:程序博客网 时间:2024/06/05 05:23


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)

 

 

由此可以知道,我们在要加载拥有入口函数的子类之前,是要首先加载这个函数的父类的。。。。。

 

原创粉丝点击