構造器里面調用其它構造器,格式方法如下:
1、使用this調用另一個重載構造器,只能在構造器中使用;
2、必須寫在構造器執行體的第一行語句;
示例如下:
import static java.lang.System.*; //-導入java.lang.System下全部的靜態成員變量--減少代碼書寫量 public class Constructor{ //-定義4個實例變量 public String name; public String color; public double weight; public int age; public static void main(String[] args){ Constructor C=new Constructor("張三","藍色",65.5,26); out.println(C.name); out.println(C.color); out.println(C.weight); out.println(C.age); } //-創建一個空的構造器 public Constructor(){ } //-創建一個包含2個參數的構造器--構造器重載 public Constructor(String name,String color){ //-部分實例變量賦值 this.name=name; this.color=color; } //-創建一個包含4個參數的構造器--構造器重載 public Constructor(String name,String color,double weight,int age){ //-構造器里面調用其它構造器,格式方法如下: //-1、使用this調用另一個重載構造器,只能在構造器中使用; //-2、必須寫在構造器執行體的第一行語句; this(name,color); this.weight=weight; this.age=age; } }
執行結果如下: