静态代码块、构造代码块、构造方法

代码如下:

 1 public class X_x {
 2     private String name;
 3     private  int age;
 4     public  X_x(String name,int age){
 5         this.name=name;
 6         this.age=age;
 7         System.out.printf("构造方法!
");
 8     }
 9     {
10         System.out.printf("构造代码块!
");
11     }
12     static {
13         System.out.printf("静态代码块!
");
14     }
15 }

调用类:

1     public class Test {
2         public static void  main(String ...args){
3            X_x x=new X_x("tom",22);
4            X_x x1=new X_x("ok",21);
5 
6         }
7     }

输出结果:

执行顺序:

先执行静态代码块。当类加载到内存中之后,不会再次执行。然后执行的是构造代码块。构造代码块每次创建对象就会执行,优先于构造器。然后执行构造器。

原文地址:https://www.cnblogs.com/evilliu/p/7728941.html