Usage of structured code block

Three usages of construction code block:
1. Construction code block: the location is outside the method in the class
2. When creating an object, first trigger the construction code block and then trigger the construction method
3. The construction code is usually used to extract the construction method Commonality.

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);
  		          }
  		     }
  		     

Guess you like

Origin blog.csdn.net/GTC_GZ/article/details/107644566
Recommended