</pre><pre class="java" code_snippet_id="559704" snippet_file_name="blog_20141223_1_4766224" name="code">package xu.jin;
class Insect{
private int i=print("hello i");
Insect(){System.out.println("Insect"+i);}
{
System.out.println("1");
System.out.println("2");
}
static{
System.out.println("3");
System.out.println("4");
}
static int print(String str){
System.out.println(str);
return 2;
}
static int x1=print("static Insect");
}
class hello extends Insect{
private int j=print(" hello j");
static int x2=print("static hello");
hello(){
System.out.println("hello"+j);
}
{
System.out.println("11");
System.out.println("22");
}
static{
System.out.println("33");
System.out.println("44");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
hello sCat=new hello();
//Insect ins=new Insect();
System.out.println("hello world");
}
}
output:
3
4
static Insect
static hello
33
44
hello i
1
2
Insect2
hello j
11
22
hello2
hello world
1、首先加载类,再初始化。想想也知道肯定先加载基类,再子类,初始化也是,子类是在基类基础上进行添加,肯定先要初始化基类再子类。
2、先初始化static的变量,在执行main()方法之前就需要进行加载。再执行main方法,如果new一个对象,则先对这个对象类的基本成员变量进行初始化(非方法),包括构造代码块,这两种是按照编写顺序按序执行的,再调用构造函数。
3、关于继承的初始化机制,首先执行含有main方法的类,观察到hello类含有基类Insect,即先加载Insect类的static变量,再加载hello类的static变量。加载完static变量之后,调用main()方法,new hello则先初始化基类的基本变量和构造代码块,再调用基类的构造方法。然后再初始化子类hello的基本变量和构造代码块,再执行子类的构造函数。