Java在構造函數中調用其它構造函數


在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 + '\'' +
                '}';
    }
}

運行結果為:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM