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

程序执行顺序-java

2014-09-07 12:10 288 查看
原文链接http://blog.163.com/shutear_bin/blog/static/195047240201231963334615/


java代码执行顺序

         一、java代码执行顺序(理解形式):1、父类静态代码块->子类静态代码块(只执行一次);

                                         
                   2、父类成员变量的初始化或普通代码块->父类构造函数;
 
                                             3、子类成员变量的初始化或普通代码块->子类构造函数。

         二、概念:               
         static代码块也叫静态代码块,是在类中独立于类成员的static语句块,可以有多个,位置可以随便放,它不在任何的方法体内,JVM加载类时会执行这些静态的代码块,如果static代码块有多个,JVM将按照它们在类中出现的先后顺序依次执行它们,每个代码块只会被执行一次。
         eg: static
{       
System.out.println("static
block of demo!");
}

         普通代码块是指在类中直接用大括号{}括起来的代码段。
          eg:
          {
System.out.println("comman
block of demo!");
           }

三、代码示例

public class Parent
{
 private Delegete delegete = new Delegete();
 
 static//加载时执行,只会执行一次
 {
System.out.println("static block of parent!");
 }

 
 public Parent(String name)
 {
System.out.println("to construct parent!");
 }
 
 {
System.out.println("comman block of parent!");
 }
}

class Child extends Parent
{
 static
 {
System.out.println("static block of child!");
 }
 
 static//可以包含多个静态块,按照次序依次执行
 {
  System.out.println("second static block of child!");
 }
 
 //普通代码块与变量的初始化等同的,按照次序依次执行
 {
  System.out.println("comman mode of child!");
 }
 
 
 private Delegete delegete = new Delegete();
 
 {
  System.out.println("second comman mode of child!");
 }
 
 //构造顺序,先执行静态块(父类、子类顺序执行)
 //执行父类成员变量的初始化或普通代码块,然后执行构造函数
 //执行子类成员变量的初始化或普通代码块,然后执行构造函数
 public Child()
 {
  super("DLH");
  System.out.println("to construct child!");
 }
 
 public static void main (String[] args) {
  Child c = new Child();  
  System.out.println("**********************************");
  Child c2 = new Child();
 }
}

class Delegete
{
 static 
 {
  System.out.println("static of Delegete!");
 }
 public Delegete()
 {
  System.out.println("to construct delegete!");
 }

 
输出结果:
 static block of parent!
 static block of child!
 second static block of child!
 static of Delegete!
 to construct delegete!
 comman block of parent!
 to construct parent!
 comman mode of child!
 to construct delegete!
 second comman mode of child!
 to const
4000
ruct child!
 **********************************
 to construct delegete!
 comman block of parent!
 to construct parent!
 comman mode of child!
 to construct delegete!
 second comman mode of child!
 to construct child!

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