從一個程序開始:

1 class dog 2 { 3 private String name; 4 private String color; 5 private int age; 6 7 dog(String name) 8 //僅給name賦值 9 { 10 this.name=name; 11 } 12 dog(String name,String color) 13 //僅給name,color賦值 14 { 15 this.name=name;//但之前有過類似代碼 16 this.color=color; 17 } 18 dog(String name,String color,int age) 19 //僅給name,color,age賦值 20 { 21 this.name=name; 22 this.color=color;//之前有過類似代碼 23 this.age=age; 24 } 25 /*以上代碼缺點,代碼重復, 26 而且如果修改最初定義的參數(如name)時, 27 需要大量修改方法中的參數(3處修改),造成不便*/ 28 } 29 30 class ConstructerDemo 31 { 32 public static void main(String[] args) 33 { 34 35 } 36 }
此時我們可以使用構造方法來調用構造方法(形式為this(實參)),來解決上述問題,改進如下:

1 class dog 2 { 3 private String name; 4 private String color; 5 private int age; 6 7 dog(String name) 8 //僅給name賦值 9 { 10 this.name=name; 11 } 12 dog(String name,String color) 13 //僅給name,color賦值 14 { 15 //this.name=name;//但之前有過類似代碼 16 this(name);//改進后 17 this.color=color; 18 } 19 dog(String name,String color,int age) 20 //僅給name,color,age賦值 21 { 22 //this.name=name; 23 //this.color=color;//之前有過類似代碼 24 this(name,color);//改進后 25 this.age=age; 26 } 27 /*以上代碼缺點,代碼重復, 28 而且如果修改最初定義的參數(如name)時, 29 需要大量修改方法中的參數(3處修改),造成不便*/ 30 } 31 32 class ConstructerDemo 33 { 34 public static void main(String[] args) 35 { 36 37 } 38 }
我們要注意的是,對this構造器的調用必須是構造器中的第一個語句。
也就是兩點要注意,一是this構造器必須放在構造器中。二是必須為構造器中的第一個語句。