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

运行结果为:

 

posted @ 2020-05-05 09:50  不皮的皮卡丘  阅读(5545)  评论(0)    收藏  举报