在Java中在構造函數中調用其它構造函數的方式與C++不同,需要使用this關鍵字,而不是像C++直接使用構造函數名來調用。
public class Good { private String gName; private double gPrice; private int gCategory; private String gCategoryName; public static void main(String[] args) { Good good = new Good("華為P30",3895.5,"手機"); System.out.println(good); } public Good(String gName, double gPrice, int gCategory) { this(gName,gPrice,gCategory,""); } public Good(String gName, double gPrice, String gCategoryName) { this(gName,gPrice,555,gCategoryName); } public Good(String gName, double gPrice, int gCategory, String gCategoryName) { this.gName = gName; this.gPrice = gPrice; this.gCategory = gCategory; this.gCategoryName = gCategoryName; } @Override public String toString() { return "Good{" + "gName='" + gName + '\'' + ", gPrice=" + gPrice + ", gCategory=" + gCategory + ", gCategoryName='" + gCategoryName + '\'' + '}'; } }
運行結果為: