Java 初始化及类的加载

下面是Think in Java中的一段代码,自己加了几行

package reusing;

import static net.mindview.util.Print.*;

class Insect {
 private int i = 9;
 protected int j;
 
 private int x2 = printInit("Insect.x1 initialized");

Insect() {
  print("i = " + i + ", j = " + j);
  j = 39;
 }
 static {
  System.out.println("Init Static block");
 }
 
 {
  System.out.println("Init block");
 }

private static int x1 = printInit("static Insect.x1 initialized");

static int printInit(String s) {
  print(s);
  return 47;
 }
}

public class Beetle extends Insect {
 private int k = printInit("Beetle.k initialized");
 
 static {
  System.out.println("Beetle static block");
 }

public Beetle() {
  print("k = " + k);
  print("j = " + j);
 }

private static int x2 = printInit("static Beetle.x2 initialized");
 private int x1 = printInit("Beetle.x2 initialized");


 public static void main(String[] args) {
  print("Beetle constructor");
  Beetle b = new Beetle();
 }
 
}

分析其类加载的过程:

(1)首先加载当前类,再加载当前类的父类,直到加载到基类,然后执行基类的static代码块,再执给基类里面的static成员变量赋值,赋值完成之后再执行子类里面的static代码块和给static成员变量赋值,以此类推。

(2)static块和成员赋值为完成之后回到基类中,给其余的非static的成员变量赋值,再执行非静态块,然后是构造方法,完成之后回到子类中继续按(2)处执行

上面的代码执行结果是:

Init Static block
static Insect.x1 initialized
Beetle static block
static Beetle.x2 initialized
Beetle constructor
Insect.x1 initialized
Init block
i = 9, j = 0
Beetle.k initialized
Beetle.x2 initialized
k = 47
j = 39

推荐阅读

深度思考Java成员变量的初始化

Java类类型的存储特点

Java中两种单例模式小结

单例模式(Singleton Pattern)

Java单例模式实例---读取配置文件

Java单例模式(Singleton)

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/7b9b23d720b4ce5aae515ade3e5db6a7.html