Java基础20-构造代码块

特点:

  • 对象一建立就运行了,而且优先于构造函数执行
  • 作用:给对象初始化的

构造代码块和构造方法的区别:

  • 构造方法是对应的对象进行初始化
  • 构造代码块是给所有的对象进行统一的初始化
 1 public class Test{
 2     public static void main(String[] args){
 3         Persion p1=new Persion();
 4         Persion p2=new Persion("小明");
 5         System.out.println(p1.country);
 6         System.out.println(p2.country);
 7 
 8     }
 9 }
10 
11 class Persion{
12     String name;
13     String country;
14     Persion(){
15         System.out.println("我是无参构造方法");
16     }
17     Persion(String name){
18         this.name=name;
19         System.out.println("我是有参构造方法");
20     }
21     {
22         System.out.println("我是构造代码块");
23         country="中国";
24     }
25 }
原文地址:https://www.cnblogs.com/shenhainixin/p/10050336.html