java中关于父类与子类的静态初始化块、普通初始化块、无参与有参方法的顺序

时间:2021-11-05 19:31:12
package practice;
class Vehicle{  
     Vehicle() { //父类构造方法 构造器 
        System.out.println("父类无参构造器");  
    }
     static {
    	 System.out.println("父类静态块初始化");
     }
     
     {
    	 System.out.println("父类普通初始化块");
     }
}  
class Test5 extends Vehicle{  
    Test5() {//子类构造方法构造器  
        System.out.println("子类无参构造器");  
    }  
    int speed;  
    Test5(int speed){//子类有参构造方法  
    	this.speed=speed;  
        System.out.println(speed);  
    }  
    static{
    	System.out.println("子类静态块初始化");
    }
    //普通的初始化块  
    {  
        System.out.println("子类普通初始化块");  
    }  
    public static void main(String[] args) {  
        Vehicle b1=new Vehicle();//    Vehicle is created  
        System.out.println("-------------------");
        Test5 b=new Test5(128);//Vehicle is created    instance initializer block invoked 128  
        System.out.println("-----------------");
        Test5 b2=new Test5(256);//Vehicle is created    instance initializer block invoked 256  
    }  
}
答案
父类静态块初始化
子类静态块初始化
父类普通初始化块
父类无参构造器
-------------------
父类普通初始化块
父类无参构造器
子类普通初始化块
128
-----------------
父类普通初始化块
父类无参构造器
子类普通初始化块
256