亲宝软件园·资讯

展开

Java中自由块的执行顺序 在Java中自由块的执行顺序

人气:0
想了解在Java中自由块的执行顺序的相关内容吗,在本文为您仔细讲解Java中自由块的执行顺序的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java,自由块,执行顺序,下面大家一起来学习吧。

下面通过例子来说明:

父类

复制代码 代码如下:

father.java

public class father {

    static{//静态块
       System.out.println("father'sSTATIC free block running");
    }

    {//非静态块
 System.out.println("father'sfree block running");
    }

    public father(){

       System.out.println("father'sconstructor running");

    }
}

子类

复制代码 代码如下:

son.java
public class son extends father{
    static{//静态块
       System.out.println("son'sSTATIC free block running");
    }

    {//非静态块
       System.out.println("son's freeblock running");
    }

    public son() {
       // TODO Auto-generated constructor stub
       System.out.println("son'sconstructor running");
    }
}

主函数所在类

复制代码 代码如下:

test.java

public class test{

      public static void main(String[] args) {

       Class f;

       try {

           System.out.println("--------beforeload father--------");

           f=Class.forName("freeblock.father");

           System.out.println("--------afterload father---------");        

           System.out.println("--------beforeinitial father object--------");

           f.newInstance();

           System.out.println("--------afterinitial father object--------");

       } catch (ClassNotFoundException e) {

           e.printStackTrace();

       } catch (InstantiationException e) {
           e.printStackTrace();

       } catch (IllegalAccessException e) {

           e.printStackTrace();
       }     
       Class s;

       try {

           System.out.println("-------beforeload son--------");

           s=Class.forName("freeblock.son");

           System.out.println("--------afterload son-------");

           System.out.println("--------beforeinitial son object----------");

           s.newInstance();

           System.out.println("--------afterinitial son object-----------");

       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       } catch (InstantiationException e) {
           e.printStackTrace();
       } catch (IllegalAccessException e) {
           e.printStackTrace();
       }
    }
}

执行结果:

--------before loadfather--------

father's STATIC free blockrunning

--------after loadfather---------

--------before initial fatherobject--------

father's free block running

father's constructor running

--------after initial fatherobject--------

-------before load son--------

son's STATIC free block running

--------after load son-------

--------before initial sonobject----------

father's free block running

father's constructor running

son's free block running

son's constructor running

--------after initial son object-----------

 

加载全部内容

相关教程
猜你喜欢
用户评论