构造代码块的用法

构造代码块的三个用法:
1,构造代码块:位置是在类里方法外
2,在创建对象时,先触发构造代码块再触发构造方法
3,构造代码快通常用来提取构造方法中的共性。

public class Test{
  		public static void main (String[] args){
  		new   Person();
  		new   Person("jack");
  				}
  		}
  		class Person{
  		     String country;
  		     {	
  		     		country = "中国";
  		     		System.out.println("构造代码块");
  		      }
  		      public  Person(){
  		      		System.out.println("无参构造"+country);
  		      }
  		      public Person(String name){
  		      			System.out.println("含参构造"+country);
  		          }
  		     }
  		     

猜你喜欢

转载自blog.csdn.net/GTC_GZ/article/details/107644566