related URL: http://www.cnblogs.com/guoyuqiangf8/archive/2012/10/31/2748909.html
Parent Class:
package com.test.testclass; public class Parent { public static int t = parentStaticMethod2(); {
System.out.println("Parent non-static block");
} static
{
System.out.println("Parent static block");
} public Parent(){
System.out.println("parent Constructor method");
} public static int parentStaticMethod(){
System.out.println("Parent Class static method1");
return 10;
} public static int parentStaticMethod2(){
System.out.println("Parent Class static method2");
return 9;
} protected void finalize() throws Throwable{
super.finalize();
System.out.println("destory parent Class"); } }
Child Class:
package com.test.testclass; public class Child extends Parent { {
System.out.println("child non-static block");
} static
{
System.out.println("child static block");
} public Child(){
System.out.println("child constructor");
} public static int childStaticMethod(){
System.out.println("child static method");
return 1000;
} protected void finalize() throws Throwable{
super.finalize();
System.out.println("destory child class");
} }
Test Class:
package com.test.testclass; public class Test { public static void main(String[] args){
//Parent.parentStaticMethod();
Child child = new Child();
} }
And the result is:
所以综上所述,类的加载顺序应该是:
父类的静态变量
父类的静态块
子类的静态块
父类的非静态块
父类的构造函数
子类的非静态块
子类的构造函数
总结: 对象的初始化顺序:首先执行父类静态的内容,父类静态的内容执行完毕后,接着去执行子类的静态的内容,当子类的静态内容执行完毕之后,再去看父类有没有非静态代码块,如果有就执行父类的非静态代码块,父类的非静态代码块执行完毕,接着执行父类的构造方法;父类的构造方法执行完毕之后,它接着去看子类有没有非静态代码块,如果有就执行子类的非静态代码块。子类的非静态代码块执行完毕再去执行子类的构造方法。总之一句话,静态代码块内容先执行,接着执行父类非静态代码块和构造方法,然后执行子类非静态代码块和构造方法。
注意:子类的构造方法,不管这个构造方法带不带参数,默认的它都会先去寻找父类的不带参数的构造方法。如果父类没有不带参数的构造方法,那么子类必须用supper关键子来调用父类带参数的构造方法,否则编译不能通过。
还有个不错的URL, mark下方便以后学习:
http://www.cnblogs.com/guanghuiqq/archive/2012/10/09/2716898.html
PS: 学习的路上,欢迎指正