博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java代码执行顺序
阅读量:6961 次
发布时间:2019-06-27

本文共 1975 字,大约阅读时间需要 6 分钟。

hot3.png

 一、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 construct 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!

转载于:https://my.oschina.net/u/268088/blog/95128

你可能感兴趣的文章
[BZOJ] 1003 [ZJOI2006]物流运输
查看>>
Vue项目中的mock数据
查看>>
关于Scott用户
查看>>
Bitmap的加载和Cache
查看>>
IOS 并发编程之NSOperation的使用
查看>>
Java基础知识回顾之六 ----- IO流
查看>>
函数调用机制2
查看>>
10. Regular Expression Matching
查看>>
HDU 4757 可持久化trie树
查看>>
web.py框架之i18n支持
查看>>
ios 学习笔记(8) 控件 按钮(UIButton)的使用方法
查看>>
PHP cURL
查看>>
Python 5 面向对象进阶
查看>>
前端性能优化(三)
查看>>
JS正则验证字符串是否是数字,判断数组已经存在的值
查看>>
洛谷P2824 排序
查看>>
PHP中的验证码类(验证码功能设计之二)
查看>>
学习React系列(三)——Refs和Dom
查看>>
团队管理中的代码评审
查看>>
迭代器
查看>>