java中父类子类静态代码块、构造代码块执行顺序

父类静态(代码块,变量赋值二者按顺序执行)

子类静态

父类构造代码块

父类构造方法

子类构造代码块

子类构造方法

普通方法在实列调用的时候执行,肯定位于上面之后了

 1 //父类A
 2 public class A {
 3 
 4      A() {
 5          System.out.println("A构造方法");
 6      }
 7 
 8     {
 9          System.out.println("A构造代码块");
10      }
11     
12          static{
13          System.out.println("A静态码块");
14      }
15 
16     public static void main(String[] args) {
17             C c1=new C();        
18         }
//子类C
public class C extends A {
    static {
        System.out.println("C的静态代码块");
    }
    {
         System.out.println("C构造代码块");
     }
     C() {
        System.out.println("C的构造方法");
    }
}

结果:

 这样就很明了了,下面稍微扩展一下,如果在main中出现 new A()呢?我们来看

 1 //父类A
 2 public class A {
 3 
 4     static{
 5          System.out.println("A静态码块");
 6      }
 7     
 8      A() {
 9          System.out.println("A构造方法");
10      }
11      
12     {
13          System.out.println("A构造代码块");
14      }
15     public static void main(String[] args) {
16             A a=new A();
17             C c1=new C();
18         }    
//子类C
public class C extends A {
    static {
        System.out.println("C的静态代码块");
    }
    {
         System.out.println("C构造代码块");
     }
     C() {
        System.out.println("C的构造方法");
    }
}

结果:

  结果先执行完父类A,只执行子类C,并不是执行完A的静态就执行C的静态,这里可能有误区。

博主实测,欢迎指正。

猜你喜欢

转载自www.cnblogs.com/walytong/p/9766308.html