例子: public class Dollar extends Money{ Rmb r=new Rmb(); public Dollar(){ System.out.println("Dollar is construct!"); } public static void main(String[] args){ new Dollar(); } }
class Money{ public Money(){ System.out.println("Money is construct"); } }
class Rmb{ public Rmb(){ System.out.println("RMB is construct"); } }
输出结果: Money is construct RMB is construct Dollar is construct!
在我们的程序中,实例化一个类对象的时候,运行顺序为:
静态块
父类构造器
本类中的块
本类的构造器
publicclassDog {
publicDog() {
System.out.println("Dog");
}
static{ //静态块
System.out.println("super static block");
}
{
System.out.println("super block");
}
}
publicclassMastiff extendsDog {
publicMastiff() {
System.out.println("Mastiff");
}
{
System.out.println("block");
}
static{
System.out.println("static block");
}
publicstaticvoidmain(String[] args){
Mastiff mastiff=newMastiff(); //实例化一个对象
}
}
输出结果:
super static block static block super block Dog block Mastiff